具有自定义标头和请求主体作为JSON字符串的跨域jquery ajax请求 [英] Cross domain jquery ajax request with custom headers and request body as JSON string

查看:112
本文介绍了具有自定义标头和请求主体作为JSON字符串的跨域jquery ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从另一个域创建一个JSON ajax request.在我认为解决了跨域问题之后,这就是我坚持的地方:

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:

我需要添加我的自定义"myCustomHeader"标头-从server开始很容易,但是从client ...看来似乎要复杂得多...

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

我们添加了它们

$.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.');
    }
});

这会生成一个带有我想要的标题的preflight标题,而没有values(CSV),但它们不会出现在request本身的标题中(如myCustomHeader=X)...

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)...

推荐答案

您可以为此使用CORS.

You can use CORS for this purpose.

示例代码:

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", "*");           

这篇关于具有自定义标头和请求主体作为JSON字符串的跨域jquery ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆