AJAX请求响应

问题描述 投票:0回答:4

我是 AJAX 新手。我正在发送一个请求,以在另一个页面上启动 PHP 代码,其中需要发生一些事情。我在该页面上有一个算法,检查所有事情是否都按正确的顺序正确完成。我需要的是将该布尔值返回到 AJAX 文件,以便它知道请求不仅已收到,而且以预期方式完成,这样我就可以添加一个 success: 函数来给出 OK/NEY给用户带来体验。

ajax request response
4个回答
3
投票

您的文件夹:

AnyFolderName
             |--- index.php
             |--- script.php

索引.php:

<!DOCTYPE html>
<html>
<head>
    <title>AJAX Request Sample</title>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script type="text/javascript">
        function submitform(){
            //get value of input whos id is username
            var username = $('input#username').val();
            //data to post to script.php
            var post = {username: username};
            $.ajax({
                url: "script.php", //<-- PHP Script where you want to post your data
                type: "POST",
                data: post,
                success: function(data){
                    //callback when request is finished.
                    //in our script.php, we just echoed the posted username, so it alerts whatever username you have input.
                    alert(data);
                }
            });
        }
    </script>
</head>
<body>
    <form id="myForm">
         <input id="username" name="username">
    </form>
    <button onclick="submitform();"></button>
</body>
</html>

脚本.php:

<?php
     //print out the posted data you have passed from the AJAX request
     echo $_POST['username'];
?>

0
投票

您可以在 AJAX 的 success 函数中返回(true 表示成功,false 表示不成功)变量。在此基础上您可以继续下一步。

虚拟示例:

$.ajax({
            url: '',
            type:'POST',
            data: {'id':id},
            dataType:'json',
            beforeSend:function(){

            },
            error : function(xhr, textStatus, errorThrown) {
                alert('An error occurred!');
            },
            success:function(response){
                if(response){
                  console.log('yes'); 
                   }
                else{
                  console.log('no');
                }

            }
            complete: function() {

            }
        });

0
投票

哦,这是我的错误。浏览了几十页,但终于在另一个线程上找到了答案(所以我的有点重复):

如何将数据从 PHP 返回到 jQuery ajax 调用

必须使用echo();而不是 return();在 PHP 文件中! 当然,还有相应的数据类型,在本例中为“文本”。


0
投票

这是我的解决方案

$.ajax(
{
    type: 'POST',
    url: '../some/file/file.php',
    async: true, //this is important!!!
    success: function(response)
    {
        if(response)
        {
            //use local environment storage to save data
            localStorage.setItem('data',response);
        }
    }
});

//To request data
some_variable = localStorage.getItem('data').trim(); //trim is important!!!
© www.soinside.com 2019 - 2024. All rights reserved.