我在跨域ajax调用中遇到json解析错误,不确定如何摆脱此问题 [英] I am getting a json parse error on a cross-domain ajax call not sure how to get rid of the issue

查看:127
本文介绍了我在跨域ajax调用中遇到json解析错误,不确定如何摆脱此问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通话看起来像这样

$.ajax({
  url: url,
  crossDomain: true,
  dataType: 'jsonp',
  success: function(){console.log('success');}
})

在服务器代码中类似

string data = callback + "(" jsonData + ")";
send("application/javascript",data);

jsonData有效,我敢肯定.我已经在线上许多JSON验证器上对其进行了测试.我也尝试过在服务器代码中将内容类型从application/javascript切换到application/json,但这没有什么区别.

The jsonData is valid, which I'm pretty sure of. I have tested it out on many json validators online. I've also tried switching the content-type from application/javascript to application/json in the server code but it does no difference.

我要使它起作用的唯一方法是重写发送给我的jquery的回调函数,并使其具有该特性,以便它调用我自己的全局函数而不是调用jquery成功函数.这是该解决方法的代码

The only way I've got this to work is override the callback function sent my jquery, and have it so that instead of calling jquery success function, it calls my own global function. And here is the code for that workaround

$.ajax({
   url: url,
   crossDomain: true,
   dataType: "jsonp",
   jsonpCallback: "onMyDataReceived"       
 })

  function onMyDataReceived(jsonData){  doStuff(jsonData ); }

但是我觉得这更多的是hack,而不是自然而然地从$ .ajax.sucess函数中获取.为什么第一个代码段会出错会有所帮助吗?

but I feel like this is more of a hack instead of having it naturally flow from $.ajax.sucess function. Any help on why the first code snippet would error out?

推荐答案

我真的不确定为什么第一个代码片段不起作用,但是尝试以下操作

I am really not sure why the first snippet didn't work, but trying the following

$.getJSON(url+"&callback=?",function(data){ console.log(data);})

以我的情况工作.

这篇关于我在跨域ajax调用中遇到json解析错误,不确定如何摆脱此问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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