请求的资源上不存在Access-Control-Allow-Origin标头

时间:2014-09-04 06:48:42

标签: javascript jquery ajax http get

DISCLAIMER: This question is a question about question. So that makes this question a meta question. It does not have any connection to the previously asked questions. If you find any resemblance, lemme tell you one thing- it's purely coincidental.

我想从我的网页发出一个AJAX请求。我一直试图这样做,但没有一种方法能够很好地完成。我发现接近现实的唯一帖子是this

我尝试过各种其他方法来自SO&其他类似的网站,但所有这些帖子只对我说了一件事。

"No 'Access-Control-Allow-Origin' header is present on the requested resource."

我知道你现在要把这个问题标记为重复,因为有很多类似的问题。现在..Lemme告诉你'一件事。我尝试过在SO中找到的每一件事,但是没有一个人能给我我想要的结果。这不是因为他们都错了。这是因为我对如何使用&em?em没有任何了解。最后......我找到了上面提供的链接。这很容易..但我需要知道关于代码的某些事情。这是我第一次听到美丽的首字母缩略词 - CORS。所以,如果有人能帮助我理解我提出的问题,那么所有人都要投票赞成。在我今年第三次庆祝生日之前,我想解决这个儿子的问题。我会告诉你'我所拥有的一切 - 资源形式和的问题。

1) A rotten server located at Elizabeth town.
2) I need to access it.
3) I am planning to make a HTTP GET request.
4) I have a url. (eg. http://whereismyweed.com)
5) I store it into a JavaScript variable. var stoner='http://whereismyweed.com'
6) I have a HTML div tag in my webpage. (<div id="myprecious"></div>)
7) I wanna display the response I get from the server inside of 'myprecious' div.
8) And last but not the least... my AJAX function. (Courtesy: some website I visited)




$.ajax({
                url: stoner,
                    data: myData,
                    type: 'GET',
                    crossDomain: true, // enable this
                    dataType: 'jsonp',
                    success: function() { alert("Success"); },
                error: function() { alert('Failed!'); },
                beforeSend: setHeader
            });

什么是&#39; myData&#39; ??它包含什么如何获得此请求的响应?什么是&#39; setHeader&#39; ??它有什么意义吗???如何在myprecious div中显示响应?我应该在功能上做些什么改变?这个功能是否正确?

太多问题,对吗?嗯......我只需要一个共同的答案吗?

1 个答案:

答案 0 :(得分:-1)

您的功能是正确的。遵循以下步骤可以实现您的目标 -

 //for getting response modify your code like 

      success:function(response){
            alert(response);
            $('#myprecious').html(response); //myprecious is id of div
     }

  // myData variable is jSon object which contains request parameter has to send.Eg.
     var myData = {'first_name':'Foo','last_name':'Bar'}  // now on server first_name and last_name treated as request parameter.


  // If server not required any special headers to validate request 'setHeader' does not require. by default $.ajax will take care of it. you can remove it.



     /// final code looks like 


         $.ajax({
            url: stoner,
                data: myData, 
                type: 'GET',
                crossDomain: true, // enable this
                dataType: 'jsonp',
                success: function(response ) { $('#myprecious').html(response);    
  },
                error: function() { alert('Failed!'); }

        });