When to use json and when jsonp with jquery $.ajax?

孤人 提交于 2019-12-10 19:20:17

问题


In our site, Some pages are SSL and some are non-SSL.

For Example:

http://www.example.com/search/patients
https://www.example.com/patients

Now I am searching patients on http://www.example.com/search/patients page and send server request to https://www.example.com/patients via jQuery $.ajax function and dataType=json. I am unable to get data.

Questions:

  1. Should I use jsonp when we request from http to https or https to http on same server?

  2. If I use SSL for both URLs then will it work with dataType=json only

Thanks


回答1:


Due to Same Origin Policy your ajax request is allowed only if: domain name, application layer protocol, and (in most browsers) port number of the HTML document running the script are the same

In your case the application layer protocol is different, that's why your script fails.

Possible solutions are:

  • JSONP, which has to be provided by the server

  • CORS, which is a more 'elegant' and clean solution, but is not yet fully supported by IE (IE7 doesn't support it, IE8 has some limitations)




回答2:


If you use SSL for both URLs it should work. Also as @Waqas Raja suggested, it would be better to use relative URLS.

e.g. $.ajax({url: '/search/patients'})




回答3:


You need to use either CORS, a proxy or JSONP to get content from a different origin. Changing scheme (from http to https or the other way around) is changing origin.

Pulling data from a secure server into an insecure page eliminates many of the benefits of using SSL.

If you fetch both the page and the data source over SSL then you can use plain JSON and don't introduce those security problems.



来源:https://stackoverflow.com/questions/10311821/when-to-use-json-and-when-jsonp-with-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!