Call external url through $.ajax in WordPress them

2019-02-19 21:50发布

My WordPress application is hosted on url http://127.0.0.1/wordpress/ and i added following script in WordPress header to get some token but it does not give any token

I copied that url ( http://127.0.0.1:8090/sample/sample/getToken ) and open in new tab it successfully return token but when i called it using $.ajax it does not return me token

  <script>   
   $().ready(function(){
      $("#signIn").click(function(){
                    alert("Display Alert Properly");
            $.ajax({ 
            type: "POST",
            url: "http://127.0.0.1:8090/sample/sample/getToken",
            contentType: "text/html",
            success: function(token)  { 
                window.open("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token, "_self", "");  });
        });

    });

4条回答
干净又极端
2楼-- · 2019-02-19 22:11

Ajax is subject to the same origin security policy.

You can read about it here: http://en.wikipedia.org/wiki/Same_origin_policy

There are workarounds for this, including JSONP

查看更多
女痞
3楼-- · 2019-02-19 22:19

Try this and see what error you get , it will help you see the actual problem

$().ready(function(){
      $("#signIn").click(function(){
                    alert("Display Alert Properly");
            $.ajax({ 
            type: "POST",
            url: "http://127.0.0.1:8090/sample/sample/getToken",
            contentType: "text/html",
            success: function(token)  { 
                window.open("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token, "_self", "");  
            },
            error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.statusText);
                    alert(thrownError);
                }    
            });
        });

    });
查看更多
Ridiculous、
4楼-- · 2019-02-19 22:20

You cannot directly access external resources via Javascript due to the Same Origin Policy implemented in modern browsers. However, there are a couple of solutions.

If the remote site offers JSONP you can utilize it to load external resources, but if they don't, you will not be able to access those resources directly.

If the remote endpoint does not offer JSONP, you will need a proxy script on your own server which accepts an AJAX request, makes the request to the external endpoint, and relays the response to your Javascript app. Be sure to secure such a script well to only accept requests to blessed endpoints, or you will have a nasty security hole to contend with.

查看更多
霸刀☆藐视天下
5楼-- · 2019-02-19 22:31

May be this will help.

You need to trigger JSONP behavior with $.getJSON() by adding &callback=? on the querystring, like this:

$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?",
function(data) {
    doSomethingWith(data); 
}); 

Reference Ben Everard's answer

查看更多
登录 后发表回答