Cross domain jquery ajax request with custom headers and request body as JSON string

六眼飞鱼酱① 提交于 2019-12-14 03:17:48

问题


I need to create a JSON ajax request from another domain. after I think I got over the cross domain issues, here is where I stuck:

I need to add my custom "myCustomHeader" header - that's easy from a server, but seems to be much more complicated from the client...

We added them

$.ajax({
    type: 'POST',
    data: put the results of your header request here,
    url: 'http://server.com/service',
    beforeSend: function (xhr) { 
        xhr.setRequestHeader('myCustomHeader', '1') 
    },
    success: function(data) {    
        alert('success.');
    }
});

This generates a preflight header with the headers I wanted, without the values (CSV), but they do not appear in the header of the request itself (as myCustomHeader=X)...


回答1:


You can use CORS for this purpose.

Example code:

jQuery.support.cors = true; 

function CrosDom_ajax(url) {
        if (window.XDomainRequest
        && $.browser.msie
        && $.browser.version < 10) {
        xdr = new XDomainRequest();
        if (xdr) {
            xdr.onload = function () {
               alert(xdr.responseText);

            };
            xdr.open("get", url);
            xdr.send();
        }
        }
        else {
            $.ajax({
                url: url,
                success: function (response) {


                },
                error: function (data) {
                }
            });
         }
    }

Also you need to Write the following code in server side, to allow cross domain access

Response.AppendHeader("Access-Control-Allow-Origin", "*");           


来源:https://stackoverflow.com/questions/15090797/cross-domain-jquery-ajax-request-with-custom-headers-and-request-body-as-json-st

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