Ajax解析json字符串返回未定义, [英] Ajax parse json string is returning undefined,

查看:270
本文介绍了Ajax解析json字符串返回未定义,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发送发布数据以返回json字符串:

I am sending a post data to get a json string back:

我的JSON字符串:

{"error":false,"success":"Added Website","website_id":"12"}

我的Ajax请求:

$('.publsher_add_website').on("submit", function() {
  show_loader();
  $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: $(this).serialize(),
    success: function(data) {
      if (data.success == false) {
        ajax_error(data.error);
        hide_loader();
      } else {
        console.debug(data);
        console.log(data.error);
        console.log(data.success);
        console.log(data.website_id);
        location.href = site_url + "publisher/websites?added=" + data.website_id + "#modal-verify";
        hide_loader();
      }
    },
    error: function() {
      hide_loader();
    }
  });
  return false;
});

现在,当我去使用返回的data时,它们都是不确定的.我使用过:

Now, when I go to use the returned data all of them are undefined.I have used:

console.debug(data);

哪个返回上面的json字符串,但是如果我尝试单独访问它们:

Which returns the json string above, but if I try to access them individually:

data.error;
data.success;
data.website_id;

他们都以undefined的身份返回这是为什么?我该如何解决?

They all return as undefined Why is this? How can I fix it?

推荐答案

您没有在$.ajax中提供dataType,因此AJAX将响应视为string,而不是对象.因此,在success函数内部,请先执行以下操作:

You haven't provided a dataType in your $.ajax, so AJAX treats the response as a string, not an object. So, inside the success function, do this first:

success: function(data) {
  data = JSON.parse(data);

这篇关于Ajax解析json字符串返回未定义,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆