未调用jQuery Ajax回调.ParserError

jQuery Ajax callback was not called. ParserError

本文关键字:回调 ParserError Ajax jQuery 调用      更新时间:2024-05-07

我有一个函数,它调用jquery ajax来调用C#开发的restful服务。代码如下

function refreshUsage(macAdd)
{
    alert(macAdd);
    ajax = $.ajax({ 
       type: "GET",    
       data: {'mac': '1'},
       dataType: "jsonp",
       jsonp:false,
       async:false,
       jsonpCallback:'blah',
       crossDomain: true,
       cache: false,
       contentType: "application/json; charset=utf-8",
       url: "http://localhost:20809/api/keyGen",      
       ajaxSuccess: function(data)
       {
        data = JSON.parse(data);
        console.log("data _" +data);
       },
       error: function(xhr, status, error) {
        if (status === 'parsererror') {
                console.log("resptext__" + xhr.responseText)
            }
          console.log("status _" +status);
          console.log("error _" +error);
       },     
       complete: function(response)
       {
        console.log("response _" +response);
       },
    });  
}
var blah = function (data) {
    alert(data);
    //do some stuff
}

当我点击这个给定的url时,它会在浏览器窗口中发送响应。但是,当我试图在ajax函数中获取响应文本时,它是未定义的,尽管成功代码是200,成功文本是成功的。我得到以下错误,没有回应:

resptext__未定义
状态分析错误
error_error:blah未被调用

这就是一个例子。试试这个:

<html>
        <head>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
            <script>
                $(document).ready(function(){
                    $.ajax({
                        url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                        dataType: 'jsonp',
                        success: function(dataWeGotViaJsonp){
                            var text = '';
                            var len = dataWeGotViaJsonp.length;
                            for(var i=0;i<len;i++){
                                twitterEntry = dataWeGotViaJsonp[i];
                                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                            }
                            $('#twitterFeed').html(text);
                        }
                    });
                })
            </script>
        </head>
        <body>
            <div id = 'twitterFeed'></div>
        </body>
    </html>

ThatGuy的例子将向您解释。

对我来说,我必须确保服务器按照jsonp回调的预期做出响应。我必须编辑php服务器的响应,如下所示

    $data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
    echo $_GET['callback'] . '('.json_encode($data).')';

如果您的服务器没有以类似的格式回复

             dataWeGotViaJsonp({"statusCode":201}) 

你会得到错误

希望这对有帮助