ajax cross domain not working in jquery

2020-06-23 08:01发布

问题:

Error :

Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8080, *', but only one is allowed. Origin 'http://localhost:8080' is therefore not allowed access.

$("#selector3").autocomplete({
            source: function(request, response) {               

                $.ajax({
                   url: "http://example.com/"+$("#selector3").val(),
                    type: "GET",
                        dataType: "json",
                        data: request,
                        processData: true,
                        data: {},

                        headers: { 
                            "Access-Control-Allow-Origin" : "*",
                            "Access-Control-Allow-Headers": "origin, content-type, accept"
                                    },

                        crossDomain: true,
                    success: function(data) {   
                        alert(data.Company_Id);
});

回答1:

Please use JSONP for cross domain scripting.

Check below sample code:

$.ajax({
    url: "http://example.com/" + $("#selector3").val(),
    type: "GET",
    dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
    data: request,
    processData: true,
    data: {},
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "origin, content-type, accept"
    },
    success: function(data) {
        alert(data.Company_Id);
    }
});


回答2:

you can't do ajax operaitons on other websites source code except you have rights. you have to to that on the server side. in php you can use cURL, in .net you can use html agility pack.



回答3:

The headers you send to the server from Javascript, should be returned by the server. If you have no access to the server this will be impossible. This means the server accepts your domain as a legal processor.

Next to that you can try a JSONP call. Check this URL: https://learn.jquery.com/ajax/working-with-jsonp/



标签: jquery ajax