Miq*_*Ali 14 ajax jquery json jquery-mobile cordova
我的ajax代码是
$.ajax({
type: 'GET',
dataType: "jsonp",
processData: false,
crossDomain: true,
jsonp: false,
url: "http://someotherdomain.com/service.svc",
success: function (responseData, textStatus, jqXHR) {
console.log("in");
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个跨域的ajax请求.
我得到了正确的请求响应,同时用firebug检查我可以看到响应.
这是我在firebug响应中以及通过Web浏览器访问此URL时的响应
{"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"}
Run Code Online (Sandbox Code Playgroud)
但我收到了错误
SyntaxError: invalid label
{"AuthenticateUserResult":"{\"PKPersonId\":8970,\"Salutation\
Run Code Online (Sandbox Code Playgroud)
我是否需要使用任何其他方法来使其工作.我想在phonegap + jquery移动应用程序中实现这一点.
此外,我没有任何访问Web服务的权限
如果我禁用Chrome网络安全,它工作正常
看起来内部JSON结构作为字符串传递.您将再次使用JSON.parse()将该数据作为对象获取.
try {
responseData = JSON.parse(responseData);
}
catch (e) {}
Run Code Online (Sandbox Code Playgroud)
编辑:尝试以下操作:
$.ajax({
type: 'GET',
dataType: "json",
url: "http://someotherdomain.com/service.svc",
success: function (responseData, textStatus, jqXHR) {
console.log("in");
var data = JSON.parse(responseData['AuthenticateUserResult']);
console.log(data);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,似乎这个Web服务返回包含另一个JSON的JSON - 内部JSON的解析内容成功.解决方案很丑,但对我有用.JSON.parse(...)尝试转换整个字符串并失败.假设您始终得到答案,{"AuthenticateUserResult":并且有趣的数据在此之后,请尝试:
$.ajax({
type: 'GET',
dataType: "text",
crossDomain: true,
url: "http://someotherdomain.com/service.svc",
success: function (responseData, textStatus, jqXHR) {
var authResult = JSON.parse(
responseData.replace(
'{"AuthenticateUserResult":"', ''
).replace('}"}', '}')
);
console.log("in");
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
Run Code Online (Sandbox Code Playgroud)
dataType必须text防止自动解析您从Web服务收到的格式错误的JSON 非常重要.
基本上,我通过删除最顶部的大括号和键AuthenticateUserResult以及前导和尾随引号来消除外部JSON .结果是一个格式良好的JSON,可以进行解析.
| 归档时间: |
|
| 查看次数: |
104370 次 |
| 最近记录: |