最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does Ajax give me a cross origin error when I can make the request from PHP? - Stack Overflow

programmeradmin3浏览0评论

I can make a GET request from PHP and get the correct response. This is the function I use:

PHP

function httpGet($url)
{
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);

    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}

A simple example:

$fakevalue='iamfake';
$url="=".$fakevalue;
$jsondata= httpGet($url);
$fake_array = json_decode($jsondata, true);
$weed_var=$fake_array['weeds']; // successfully obtained weed.

This function returns the response from the server.

Now I am trying the same HTTP GET request in AJAX, but I can't get the response.

Initially I thought the problem was with the JavaScript function that I use. Google provided with me lots of JavaScript functions for performing the HTTP GET request but they all had the same problem. The request returns an error instead of the data that I got when I used PHP.

JAVASCRIPT

var fakevalue = "iamfake";

var fake_data = {
    fakeparameter: fakevalue
};

$.ajax({
    url: "",
    data: fake_data,
    type: "GET",
    crossDomain: true,
    dataType: "json",
    success: function(a) {
        $("#getcentre").html(a);
    },
    error: function() {
        alert("Failed!");
    }
});

Error from JavaScript

XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.`

I know you are going to tell me to use CORS, but if it was because of the absence of 'Access-Control-Allow-Origin' header, then how did I get response for the same service in PHP?

I can make a GET request from PHP and get the correct response. This is the function I use:

PHP

function httpGet($url)
{
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);

    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}

A simple example:

$fakevalue='iamfake';
$url="http://fakeurl.?fakeparameter=".$fakevalue;
$jsondata= httpGet($url);
$fake_array = json_decode($jsondata, true);
$weed_var=$fake_array['weeds']; // successfully obtained weed.

This function returns the response from the server.

Now I am trying the same HTTP GET request in AJAX, but I can't get the response.

Initially I thought the problem was with the JavaScript function that I use. Google provided with me lots of JavaScript functions for performing the HTTP GET request but they all had the same problem. The request returns an error instead of the data that I got when I used PHP.

JAVASCRIPT

var fakevalue = "iamfake";

var fake_data = {
    fakeparameter: fakevalue
};

$.ajax({
    url: "http://fakeurl.",
    data: fake_data,
    type: "GET",
    crossDomain: true,
    dataType: "json",
    success: function(a) {
        $("#getcentre").html(a);
    },
    error: function() {
        alert("Failed!");
    }
});

Error from JavaScript

XMLHttpRequest cannot load http://fakeurl.?fakeparameter=fakevalue. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.`

I know you are going to tell me to use CORS, but if it was because of the absence of 'Access-Control-Allow-Origin' header, then how did I get response for the same service in PHP?

Share Improve this question edited Feb 10, 2016 at 8:49 Quentin 944k132 gold badges1.3k silver badges1.4k bronze badges asked Sep 10, 2014 at 10:38 user3962692user3962692 6
  • 9 It's the browser who denies your request to a domain different than your current one. When you use PHP, the server running your PHP code acts as a client and performs a GET request. When a browser performs an AJAX request, the remote server (if not the same domain) has to explicitly allow it - the server sends Access-Control-Allow-Origin back. There's the difference and yes, CORS is the answer. – N.B. Commented Sep 10, 2014 at 10:41
  • Google Chrome, Mozilla Firefox, IE- I tried this in all these 3 browsers. Error is same. Then how is this because of browser?? @ N.B. – user3962692 Commented Sep 10, 2014 at 10:43
  • 1 Quentin explained it really well in his answer. Every browser MUST implement this in order to conform to the standard, which exists mostly because of security. – N.B. Commented Sep 10, 2014 at 10:43
  • @Hi_Daddy — Because they standardised on a mon security model. It's a feature, not a bug. – Quentin Commented Sep 10, 2014 at 10:44
  • 1 Even reading en.wikipedia/wiki/Cross-origin_resource_sharing should have told you all you need to know already … you either need to learn how to do some basic research, or how to understand explanations on technical stuff in the first place. – C3roe Commented Sep 10, 2014 at 10:50
 |  Show 1 more ment

3 Answers 3

Reset to default 16

With PHP (or anything else running on your server, or a standalone application (including those installed as a browser extension)), you are requesting data from Bob's server using your credentials (your cookies, your IP address, your everything else).

With Ajax, you are asking Alice's browser to request data from Bob's server using her credentials and then to make that data available to your JavaScript (which can then send it back to your server so you can see it yourself).

Bob might give different data to Alice then he would give to you. For example: Bob might be running Alice's eBanking system or pany intranet.

Consequently, unless Bob's server tells Alice's browser that it is OK to make that data available to you (with CORS), the browser will prevent your JavaScript from accessing that data.

There are alternatives to CORS, but they involve either distributing the data using a file type that isn't designed to be a data format (JSONP) (which also requires Bob's server to cooperate) or having your server fetch the data from Bob and then make it available through a URL on your server (or some bination of the two like YQL does) (which means that you get the data Bob will give to you and not the data Bob will give to Alice).

Simple answer: PHP isn't affected by CORS. It is a restriction placed by the browser on client-side code, so that the accessed URL gets to allow or deny the request.

You are running into CORS, because you are doing an XMLHttpRequest request from your browser to a different domain than your page is on. The browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. Try this: http://www.html5rocks./en/tutorials/cors/

If you only want to launch a GET request, you might try using JSONP datatype="jsonp". Examples: http://www.sitepoint./jsonp-examples/

发布评论

评论列表(0)

  1. 暂无评论