問題:ajax跨域訪問報(bào)錯(cuò)501
運(yùn)行下面的代碼會(huì)報(bào)錯(cuò)501
$.ajax({ type: "POST", url: "http://192.168.1.202/sensordata.php", contentType:'application/json; charset=utf-8', data: JSON.stringify(ajaxPostData), dataType:'json', success: function(data){ //On ajax success do this console.info("success."); if (data["status"] == "ok"){ alert("Settings is Ok. The Machine is rebooting."); } }, error: function(xhr, ajaxOptions, thrownError) { //On error do this console.info("error."); if (xhr.status == 200) { alert(ajaxOptions); } else { alert(xhr.status); alert(thrownError); } } });
解決方法:
去掉 contentType:'application/json; charset=utf-8'
原因:
1 在跨域的時(shí)候,除了contentType為application/x-www-form-urlencoded, multipart/form-data或者text/plain外,都會(huì)觸發(fā)瀏覽器先發(fā)送方法為OPTIONS的請(qǐng)求。
2 比如說,你原來的請(qǐng)求是方法方法POST,如果第一個(gè)請(qǐng)求返回的結(jié)果Header中的Allow屬性并沒有POST方法,
3那么第二個(gè)請(qǐng)求是不會(huì)發(fā)送的,此時(shí)瀏覽器控制臺(tái)會(huì)報(bào)錯(cuò),告訴你POST方法并不被服務(wù)器支持。
參考文檔:http://www.foreverpx.cn/2016/06/22/cross_content_type/
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長站。
|
新聞熱點(diǎn)
疑難解答
圖片精選