简体   繁体   中英

JQuery .post() not returning data

I am trying to pass parameters to the TinyPaste API. I have the following JQuery script in an HTML file,

$.post("http://tinypaste.com/api/create.json", 
    { 
     "paste": "This is test paste", 
     "title": "Test",
     "is_code": 0,
     "is_private": 1
    },
    function(data) {
        console.log(data);
    }
);

As seen in the Firefox's Web Console, I can see that the request is made and is successful (The content length of the response is as expected). But the callback function is not printing anything in the console window.

What am I doing wrong here?

you should write like this

  $.post("http://tinypaste.com/api/create.json", 
            { 
             'paste': "This is test paste", 
             'title': "Test",
             'is_code': 0,
             'is_private': 1
            },
            function(data) {
                console.log(data);
            },
            'jsonp'
        );

You must send also a data type to server, means jsonp .

看起来您是从您的网站向另一个域发出请求,这违反了浏览器的“相同来源政策”,您需要使用JSONP来解决此问题。

EDIT: POST does not work for cross domain USE $.getJSON instead

$.getJSON("http://tinypaste.com/api/create.json", 
    { 
     "paste": "This is test paste", 
     "title": "Test",
     "is_code": 0,
     "is_private": 1
    },
    function(data) {
        console.log(data);
    }
);

It is entirely possible the API does not serve JSONP, in which case you will need to resort to alternate methods

The major (and only) problem with the script posted in the question is that it is making a cross domain HTTP/POST request while on a normal webpage. I previously believed you were working on some browser extension, which if configured properly will allow you to have cross-domain requests. HTTP/POST will just not work in your case. Although there are hacks to get HTTP/GET working, like using the script tag, and JSONP.

In your case, what I suggest is let your server (which serves out your page) carry out the request for you.

The process will be:

  • You submit a request to the server with the parameters for tinypaste.
  • The server side script will do the HTTP/POST to tinypaste, and fetch the response. This response is sent across to the browser.
  • Browser gets the response. (and may be redirects or something)

Or as @charlietfl suggests, you could use YQL and Jquery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM