javascript - 当 dataType 设置为 JSONP 时读取 JSON 响应

标签 javascript jquery ajax cross-domain jsonp

我正在尝试发出 JSONP 请求以允许跨域。情况是我的服务器不处理 JSONP 请求,它将此请求理解为 JSON 并以 JSON 对象响应:{result: 1}

这是我的 ajax 请求:

jQuery.ajax({
    type : 'POST',
    url : "https://example.com/addUser",
    data : {
        firstName : 'firstName',
        lastName : 'lastName',
        email : 'email@yopmail.com'
    },
    crossDomain : true,
    jsonpCallback: "jsonpCallback",
    success : function(data) {
        alert(data);
    },
    complete : function(jqXHR, textStatus) {
                //can do something here
    },
    error : function (xhr, textStatus, errorThrown) {
        if(errorThrown=="jsonpCallback was not called") {
                console.log('caught it!');
        }
            },
    dataType : 'jsonp'
});

从窗口控制台读取:

Resource interpreted as Script but transferred with MIME type text/json: "https://example.com/addUser…Name=firstName&lastName=lastName&email=email%40yopmail.com&_=1359646137496".

Uncaught SyntaxError: Unexpected token : 

caught it!

正如预期的那样,它抛出 parseerror 异常,我尝试处理它。但我的问题是,由于浏览器实际上正在获取响应 {result:1},是否有一种方法可以解析它?

最佳答案

使用数据类型:'json'

$.ajax({
 url: getinstruments,
  dataType: 'json',
  success: function(data) {
  alert (data.firstName);
}
});

关于javascript - 当 dataType 设置为 JSONP 时读取 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14629399/

相关文章:

javascript - 我需要将键值对的对象转换为单独的列表项

javascript - 从 html 表单的文本字段中读取并检查用户的输入

javascript - 轻巧的替代Sammy.js

ajax - Google Chrome的Advanced REST客户端如何发出跨域POST请求?

html - Ajax 从数据库更新内容并在单击按钮时显示

javascript - $q.all 中的 Angular promises 没有被拒绝

javascript - 关闭 Canvas 导航默认打开/关闭

javascript - 为什么ready()里面的函数,刷新页面的时候不系统执行?

jquery - 如何在 jQuery 中使元素可拖动?

影响 AJAX 控件的 CSS