【问题标题】:Getting incorrect response in JsonP在 JsonP 中得到不正确的响应
【发布时间】: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


【解决方案1】:

我找到了答案。额外的数字通过 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'}" . ')';

【讨论】:

    【解决方案2】:

    您的代码中有一些内容会在行前打印数字(屏幕截图上的 2311) print "processJSON({'result':'$result'})";

    标识符前的数字使 javascript 代码无效。

    【讨论】:

    • var code="code="+code;这是在使用 $ajax 方法将代码发送到服务器之前定义代码的正确语法吗???
    猜你喜欢
    • 2013-10-15
    • 2018-05-12
    • 2018-08-30
    • 2021-08-17
    • 2013-11-22
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2019-01-19
    相关资源
    最近更新 更多