我尝试在我的JavaScript中接收PHP响应。
我的PHP看起来像这样:
一些代码 if(...) 回显"1"; 否则回显"2";
JavaScript:
函数 GetChoice() { var 返回="; $.ajax({ 异步:假, 缓存:假, 网址: "http://mydomain.com/script.php", 类型:"开机自检", 数据类型:"文本", 成功: 函数(数据) { 返回 = 数据; } }); 返回返回; } var r = GetChoice(); 警报(r);
但GetChoice()
什么也没得到。怎么了?
UPD:如果javascript和php脚本在同一台服务器上,它就可以工作。我在不同域中的脚本。
试试这个:
温度1.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>
温度2.php
<?php
echo $_REQUEST["name"];
?>
它的工作....!
试试这个:
function GetChoice() {
var returned = "";
$.ajax({
async:false,
cache:false,
url:"http://mydomain.com/script.php",
type:"POST",
dataType:"text",
success:function (data) {
alert(data);
}
});
}
问题是,在您的示例中,$.ajax 会立即返回,并且下一个语句 return result; 在您作为成功回调传递的函数甚至被调用之前执行。这是解释。如何从异步调用返回响应?
运气
GetChoice() 在成功运行的回调之前不会返回任何内容。
回调(即定义为成功参数的函数)在从服务器请求数据之前不会触发。
这是异步的(AJAX 中的 A),因此其余代码继续导致 GetChoice() 函数在运行回调之前返回
这是脚本
<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个文件。刚刚在我的编辑器中对此进行了测试并工作..
function GetChoice() {
var returned="";
$.ajax({
url: "../script.php",
type: "POST",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);