1

我尝试在我的 JavaScript 中接收 PHP 响应。

我的 PHP 看起来像这样:

一些代码

    if(...) echo "1";

    否则回显“2”;

JavaScript:

    函数获取选择(){
        变种返回=“”;
        $.ajax({
            异步:假,
            缓存:假,
            url: "http://mydomain.com/script.php",
            类型:“发布”,
            数据类型:“文本”,
            成功:函数(数据){
                返回=数据;
            }
        });
        返回返回;
    }

    var r = GetChoice();
    警报(r);

GetChoice()什么也不返回。怎么了?

UPD:如果 javascript 和 php 脚本在同一台服务器上,它可以工作。我在不同领域的脚本。

4

6 回答 6

2

尝试这个 :

temp1.php

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>


  function GetChoice() {
        var returned = "";
        $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: "http://localhost/temp2.php",
                data: { name: "John"}
                }).done(function( msg ) {                        
                        returned = msg;
                });
         return returned;
    }

    var r = GetChoice();
    alert(r);

</script>

temp2.​​php

<?php

        echo $_REQUEST["name"];        
?>

它的工作......!

于 2012-05-02T08:32:42.647 回答
1

尝试这个:

    function GetChoice() {
    var returned = "";
    $.ajax({
        async:false,
        cache:false,
        url:"http://mydomain.com/script.php",
        type:"POST",
        dataType:"text",
        success:function (data) {
            alert(data);
        }
    });
}
于 2012-05-02T08:17:38.843 回答
1

问题是,在您的示例中,$.ajax 立即返回,并且下一个语句 return result; 在您作为成功回调传递的函数甚至被调用之前执行。这里是解释。 如何从异步调用返回响应?

运气,

于 2017-02-17T20:56:00.993 回答
0

GetChoice() 在成功的回调运行之前不会返回任何内容。

回调,即您定义为成功参数的函数,在从服务器请求数据之前不会触发。

这是异步的(AJAX 中的 A),因此其余代码继续导致 GetChoice() 函数在回调运行之前返回

于 2012-05-02T08:16:05.133 回答
0

这是脚本

<script type="text/javascript">
$.ajax({
async:false,
cache:false,
url:"http://path.com/to/file",
type:"POST",
dataType: "html",
data: 'data',
success: function(data){
    alert(data);
}

});

在你的 PHP 文件中写下这段代码

<?php

function test()
{
    $str = 'This is php file';
    return $str;
}

echo test();

?>

确保 php 文件的路径正确,并将脚本添加到另一个 PHP 文件中。基本上你需要2个文件。刚刚在我的编辑器中测试了这个并且可以工作..

于 2015-05-05T05:15:40.067 回答
0
function GetChoice() {
    var returned="";
    $.ajax({
        url: "../script.php", 
        type: "POST",
        success: function(data) { 
            returned = data;
        }
    });
    return returned;
}

var r = GetChoice();
alert(r);
于 2020-08-19T15:49:49.223 回答