ajax请求没有运行成功函数

时间:2015-07-30 09:58:04

标签: jquery ajax

我有以下功能:

function loadRoles(){
console.log("load roles");
var data = {
  "fn" : "rLoad",
  "projectID" : sProject,
  "ajax" : "true"
};
$.ajax({
  type: "GET",
  url: SERVICE_URL, //Relative or absolute path to response.php file
  data: data,
  contentType: "application/json",
  success: function(response) {
    var i, list, tList;
        console.log("responding");
        lsRoles = response;

        for (i = 0; i < response.length; i++) {
            //list += formatCheckBoxItem(response[i]);
            tList += formatListItem(response[i].name[0], response[i].id[0]);
        }
        console.log(tList);  //////////////////////////////////////////////////////////         list has the text "undefined" at the start of it... i cannot work out why 0.o
        //$("#cbProjects").html(list).trigger("create");
        $("#lsRoles").html(tList).listview('refresh');
  }
});
}success: function(response) {
    alert("The project " + name + " has been added and can be viewed in the QLearn App");
  }
});
}

我知道sProject已定义

我的问题是success选项永远不会运行,或者至少它没有进入console.log("responding");

我从服务器收到200响应....

我不知道这里还有什么问题。想法?

3 个答案:

答案 0 :(得分:1)

也要捕获错误回调并检查其参数。

SERVICE_URL是否属于同一个域? (同源政策)

浏览器 - 开发者工具的网络标签显示什么作为答案?

获取有用错误消息的一种方法是:

$.ajax({
    type: "GET",
    url: SERVICE_URL,
    dataType: "json",
    success: function(resp) {
        console.log("success");
    },
    error: function(xhr, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

请注意,如果您将响应声明为JSON,则如果响应无效,则请求将失败。在您的情况下,您必须删除&#34; adultScotland&#34;拥有有效的JSON。

答案 1 :(得分:0)

你使用+=并且在第一次运行时你的字符串还不是字符串。所以它试图在第一次运行时计算:

undefined + 'some string'

首先将列表初始化为空字符串:

var i, list, tList = "";

答案 2 :(得分:0)

好的,所以我有点解决了这个问题,我从请求中取得了成功,并将名为loadRoles()的行更改为:

loadroles().done(function(response{
   console.log(response)
})
.fail(function(response){
    console.log(response)
});

现在我能够在日志中显示响应,但是发送响应的是.fail()

响应现在看起来像这样:readyState: 4, responseText: "[{"id":{"0":"projectM"},"name":{"0":"Project Manager"}}]", status: 200, statusText: "OK"

它有效,所以......嗯!但如果有人能说明为什么它在运行fail()我会很高兴