No 'Access-Control-Allow-Origin' header is present on the requested resource ajax jquery phonegap
我尝试在Ripple Emulator上运行PhoneGap应用程序,并使用jQuery中的Ajax方法从webservice.asmx调用方法,但得到了cors错误:
XMLHttpRequest cannot load https:
ippleapi.herokuapp.com\xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=http%3A//www.my-domain.com/WebService.asmx/selectData. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:\localhost:4400' is therefore not allowed access. The response had HTTP status code 503.
我的Ajax方法:
$Ajax({类型:"POST",交叉域:正确,网址:"http://www.my-domain.com/webservice.asmx/selectdata",数据:json.stringify(campaigndata)contenttype:"application/json;charset=utf-8",数据类型:"json",成功:函数(msg){var响应=msg.d;var resultLoop=$.parsejson(响应);console.log(响应)}错误:函数(xhr、ajaxOptions、thrownerrror){$.mobile.loading("隐藏");警报("状态:"+xhr.status+"ThrownerError:"+ThrownerError+"AjaxOption:"+AjaxOptions);}(});
无法解决这个问题,不知道我在哪里做错了什么或错过了什么我必须修改代码以便它与服务器通信并获取数据。
在Ripple Emulator上运行PhoneGap应用程序,将跨域代理设置更改为"禁用",它工作正常。
您可以在服务器端代码中添加此方法(post、delete等),也可以使用chrome插件访问控制allow headers。类似于PHP
1 2 3 | header("Access-Control-Allow-Origin: http://localhost:8080"); header("Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE, PUT"); header("Access-Control-Allow-Credentials: true"); |
对于跨域Ajax结果,可以使用jsonp,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $.ajax({ type:"POST", url:"http://www.my-domain.com/WebService.asmx/selectData", data: JSON.stringify(campaignData), contentType:"application/json;charset=utf-8", dataType:"jsonp", success: function(msg) { var response=msg.d; var resultLoop=$.parseJSON(response); console.log(response) }, error: function(xhr, ajaxOptions, thrownError) { $.mobile.loading('hide'); alert("status :"+xhr.status +" thrownError :"+ thrownError +" ajaxOption :"+ ajaxOptions); } }); |
您还需要在Web方法"callback"中添加一个参数,服务器端的字符串类型为:
1 2 3 4 5 | selectData(string callback){ var JSONString = new JavaScriptSerializer().Serialize(""); //JSONString is a json format return callback+"("+JSONString +" )"; } |
有关详细信息,请参阅http://www.niceonecode.com/q-a/javascript/ajax/cross-domain-ajax-request-to-a-json-file-using-jsonp/20154。