【发布时间】:2013-12-12 11:57:51
【问题描述】:
我正在使用$.ajax 方法将数据从index.php 文件发送到另一个exec.php 文件并执行该文件上的数据,当我使用jsonp 回调发送回输出数据时,我在index.php 上得到不正确的数据.我还将相同的输出数据写入exec.php 的 txt 文件中,并且我在 txt 文件中得到了正确的数据。
这是我在 index.php 中的 ajax 调用
$.ajax({
type: 'GET',
url: 'exec.php',
dataType: 'JSONP',
data: {code : code},
success: function(data)
{
alert(data);
$(loader).addClass('hidden');
var stdout = $(form).children('.stdout');
if (data.search("Parse error")>0)
{
var str = data.replace('<b>Parse error</b>: ','');
$(stdout).html(str);
$(stdout).removeClass('hidden');
}
else
{
$(stdout).html(data);
$(stdout).removeClass('hidden');
}
},
error: function (status,req,err) {
var errorMessage = err || req.statusText;
alert(errorMessage);
}, // When Service call fails
responseType: "jsonp"
});
这是我来自 exec.php 的 json 回调代码
$result = str_replace('"','\"', $script_output);
$script_output = str_replace('"','\"', $script_output);
$file = fopen("test.txt","w");
echo fwrite($file,$script_output);
fclose($file);
//print "processJSON({'result':'$result'})";
header('Content-Type: application/jsonp');
echo $_GET['callback'] . '(' . "{'result' : '$result'}" . ')';
现在这是我在 firebug 中得到的响应。
截图 - http://screencast.com/t/nqdAR7JedMk 我通过 ajax 方法的错误发出警报 截图 - http://screencast.com/t/5RRlYiha2C0
请告诉我我做错了什么
【问题讨论】:
-
您提供的代码中的任何内容都不会创建该响应。 (并且不要向我们展示错误消息和响应的图片,请在问题中引用它们)
-
为什么要使用 JSONP?它应该只用于跨域请求并且链接到 exec.php 不是跨域的......它是否适用于 JSON dataType?
-
我将输出写入一个文本文件,之后我使用了 json 回调函数。并在文本文件中写入所需的输出。所以我不认为我在这里没有提供的代码会生成响应
-
剩下的代码在哪里,如果你的jsonp响应函数是静态的,你必须告诉jquery它是什么。 (jsonpCallback: "callbackName")
-
我正在使用 jsonp 进行跨域
标签: javascript php jquery ajax json