[英]Cross Domain JavaScript calls using JSONP or CORS
如何在客戶端和服務器中使用jsonp和CORS在網頁上實現跨域ajax調用。
例如,在www.mytestsite.com
,要對www.otherdestinationserver.com
進行ajax調用,如何使用JSONP
或CORS
實現?
最后,我在研究完所有其他帖子后找到了一些解決方案。 我正在為這兩種方法寫答案。
1.僅在沒有CORS的情況下使用JSONP:
如果使用JSONP,則始終需要進行服務器端更改以使用callback
方法獲取json響應。 此外,callback
方法必須存在於javascript
才能執行。 所以在下面的例子中,當我們調用目標url時,如果我們得到響應為myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } })
,那么我們必須有一個javascript method
名為myCallBackMethod
javascript method
。 使用jsonp,cookies can also be shared across domains
callback
方法是myCallBackMethod
。 此名稱可以是任何內容,除了javascript
的名稱和response jsonp string must match
客戶/ javascript:
function makeTheCall(queryString) { var destinationUrl = "www.otherdestinationserver.com"; $.ajax({ type: 'GET', url: destinationUrl + queryString, dataType: 'jsonp', jsonpCallback: 'myCallBackMethod', async: false, // this is by default false, so not need to mention crossDomain: true // tell the browser to allow cross domain calls. // success: successResopnse, jsonpCallback will call the successCallback // error: failureFunction jsonp does not support errorCallback. So cannot use this }); } window.myCallBackMethod = function(data) { successResponse(data); } successResponse = function(data) { //functionality goes here; } // the json response from the server when calling the url must be in the below format only. myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } })
2.僅在沒有JSONP且沒有URL REWRITES的情況下使用CORS:
如果使用CORS,則總是need to make changes on server and client/javascript
。 在這種方法中,no need to get any callback
方法作為json響應的一部分。 響應must be a pure json
。 但是,在目標服務器上進行適當的代碼更改以允許請求通過。 因此需要在response
對象中設置header
。
客戶/ javascript:
function makeTheCall(queryString) { var destinationUrl = "www.otherdestinationserver.com"; $.ajax({ type: 'GET', url: destinationUrl + queryString, dataType: 'json', // use json only, not jsonp crossDomain: true, // tell browser to allow cross domain. success: successResopnse, error: failureFunction }); } successResponse = function(data) { //functionality goes here; } failureFunction = function(data) { //functionality goes here; }
在服務器上,添加以下標頭。
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Here need to give the origin url (the url in the address bar of the page which is making request). Using * means allow any value
在客戶端/ javascript上:
xhrFields: {
'withCredentials': true // tell the client to send the cookies if any for the requested domain
}
在服務器上:
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
Access-Control-Allow-Credentials
,則會對標頭Access-Control-Allow-Origin
的值進行限制。 never be * if we want to use Access-Control-Allow-Credentials header
它never be * if we want to use Access-Control-Allow-Credentials header
應該never be * if we want to use Access-Control-Allow-Credentials header
。 因此,給出確切的域名。 服務器更新:
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com"); // Give the origin url (the url in the address bar of the page which is making request).
最終客戶端/ javascript :(僅限CORS方法)
function makeTheCall(queryString) { var destinationUrl = www.otherdestinationserver.com; $.ajax({ type: 'GET', url: destinationUrl + queryString, dataType: 'json', // use json only, not jsonp crossDomain: true, // tell browser to allow cross domain xhrFields: { 'withCredentials': true // tell the client to send the cookies if any for the requested domain }, success: successResopnse, error: failureFunction }); } successResponse = function(data) { //functionality goes here; } failureFunction = function(data) { //functionality goes here; }
最終服務器代碼:(僅限CORS方法)
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com");
3.僅使用CORS使用URL REWRITE FILTER設置RESPONSE HEADERS:
如果應用程序使用url重寫過濾器(主要是所有Web應用程序都使用),這將使實現更容易。 在上面的方法2中,不是遵循最終服務器代碼:(僅CORS方法) ,而是按照以下URL更改xml(url重寫過濾器)。
如何使用urlrewritefilter將我們從請求獲得的origin或referer值設置到response-header中
下面粘貼相同的代碼以供快速參考。
<rule enabled="true" match-type="regex">
<name>Enabling CORS Headers</name>
<from>^/path/someMorePath.*$</from>
<condition name="origin" operator="equal">([a-z]+)</condition>
<set type="response-header" name="Access-Control-Allow-Origin">%1</set>
<set type="response-header" name="Access-Control-Allow-Credentials">true</set>
如果你無法控制服務器端,你可以像我一樣工作
僅限客戶端。
如果您可以控制服務器端,則可以使用服務器端解決方案。 我不是在這里討論它。
只在客戶端,解決方法是
使用dataType:'jsonp',
async function get_ajax_data(){
var _reprojected_lat_lng = await $.ajax({
type: 'GET',
dataType: 'jsonp',
data: {},
url: _reprojection_url,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
console.log(data);
// note: data is already json type, you just specify dataType: jsonp
return data;
}
});
} // function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.