在Javascript中访问数组

时间:2015-05-17 17:09:56

标签: javascript php ajax

我似乎无法理解为什么我无法访问我通过PHP发回的数组。

我在AJAX拨打电话时发回:$response['success'] = true;

我在PHP文件中通过echo json_encode($response);执行此操作。

现在我想在Javascript中访问它,但是response.success不起作用,它记录了未定义的'在控制台中。现在我检查响应,就是这样:{"success":false}

但如果我检查if(response.success),它总是发回false,因为response.success is undefined。有谁知道我的意思和导致这个问题的原因是什么?

这是我的AJAX电话:

$$.ajax({
    type: 'POST',
    url: url + "applogin.php",
    crossDomain: true,
    data: {
        username: e,
        password: p
    },
    //dataType: 'json', 
    success: function(response) {
        console.log(response);

        if (response["success"]) {

            window.localStorage["username"] = e;
            window.localStorage["password"] = md5(p);

            mainView.router.loadPage('beurslist.html');
        } else {

            console.log("Your login failed");
        }
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
    },

}); 

2 个答案:

答案 0 :(得分:2)

@SZenC的答案很好,关于最佳实践有一点意见:

jQuery没有将响应识别为JSON的原因是因为服务器可能没有发送Content-type标头,所以只需向服务器端代码添加一个调用 -

header('Content-type: text/json');

在每个API调用中,您不需要显式调用JSON.parse,您将更好地与测试工具集成,并且对于使用/将要使用的其他人,您的应用程序将更好地自我记录这段代码(包括你自己,你的代码需要一些未来的维护)。

在任何情况下,建议您通过明确指定dataTypejson或使用快捷方法(例如{{1})进行API调用来记录客户端的预期输入。 }。

答案 1 :(得分:1)

您的ajax-call将返回一个字符串,您需要使用JSON.parse对其进行解码。那你就得到这样的东西了。

$$.ajax({
  type: 'POST',
  url: url + "applogin.php",
  crossDomain: true,
  data: {
    username: e,
    password: p
  },
  //dataType: 'json', 
  success: function(r) {
    var response=JSON.parse(r)
    console.log(response);
    if (response["success"]) {
      window.localStorage["username"] = e;
      window.localStorage["password"] = md5(p);
      mainView.router.loadPage('beurslist.html');
    } else {
      console.log("Your login failed");
    }
  },
  error: function(jqXHR, textStatus, errorThrown) {
    console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
  }
});