简体   繁体   中英

Ajax call does not return json into website body

I'm trying to return some JSON from an AJAX call and put it into the html body but I'm struggling with the below code. Can anyone tell me where I am going wrong please?

 $("button").click(function() { $.ajax({ url: 'http://jsonplaceholder.typicode.com/todos/1', type: "POST", dataType: 'json', data: ({ type: 'main' }), success: function(result) { $("#result").html(result); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <button id='buttonJSONP'>Echo JSONP</button> <div id='result'></div> 

You need to make the request using a get , otherwise you need to look into your api for making post requests.

If it is a post , data doesn't look like this ({}) . Remove the parentheses and just use braces {} .

Using a get you need to move your data object into the url as well, because get requests don't have a body.

 $("button").click(function() { $.ajax({ url: 'http://jsonplaceholder.typicode.com/todos/1?type=main', type: "GET", dataType: 'json', success: function(result) { $("#result").html(Object.values(result).join(',')); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <button id='buttonJSONP'>Echo JSONP</button> <div id='result'></div> 

There are some issues in your code -

  1. as this is a post request you need to change your input as below also remove ( and )

    data: { "type": "main" }

  2. the API URL is also not correct for POST request, you will get 404 error even if the input is correct. The correct URL for POST will be as below -

url: 'http://jsonplaceholder.typicode.com/todos/'

Reference : Fake JSON api documentation

So your complete code should be like below -

 $("button").click(function() { $.ajax({ url: 'http://jsonplaceholder.typicode.com/todos/', type: "POST", dataType: 'json', data:{ "type": "main" }, success: function(result) { $("#result").html(Object.values(result).join("-")); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <button id='buttonJSONP'>Echo JSONP</button> <div id='result'></div> 

The response status will be HTTP 201.

In the example above you're trying to post data into a Get url.

if you want to return json response from this url you must use GET instead of POST, your code should look like:

$("button").click(function() {
  $.ajax({
    url: 'http://jsonplaceholder.typicode.com/todos/1',
    success: function(result) {
      console.log(result);
      $("#result").html(result.key);
    }
  });
});

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