AJAX从未成功

I have a GET API that gives me the following result:

enter image description here

The following code, tries to get this JSON information:

<script>
   jQuery(document).ready(function ($)
   {       
      $.ajax({
         url: 'http://localhost:15840' + '/totem/GetRestaurants',
         type: "GET",
         dataType: "jsonp",
         crossDomain: true,
         complete: function (data)
         { 
            alert (data)
            for (var restaurant in data)
            {
               document.getElementById('restaurants').innerHTML = '<li class="gallery-image" > <a href="3.html" class="thumb"><img src="img/restaurante-02.jpg" alt="" /><div class="gallery-text"><span>FOOD RESTAURANT</span></div></a></li >'
             }   
          },
          error: function () {
             alert("error");
          }
       });
    });
</script>

The error method always get executed, and the complete alert just shows the following information:

enter image description here

But If I go to chrome inspector, the responce looks good:

enter image description here

enter image description here

Why is this happening?

EDIT:

With the following code, nothing happens:

<script>
    jQuery(document).ready(function ($)
    {       
        $.ajax({
            url: 'http://localhost:15840' + '/totem/GetRestaurants',
            type: "GET",
            dataType: "jsonp",
            crossDomain: true,
            success: function (data)
            {
                alert ("hello success")
            }
        });
    });
</script>

You said:

dataType: "jsonp",

… but the screenshot of the response shows that is JSON not JSONP.

You need to either:

  1. Set the dataType to "json"
  2. Change the server to respond with JSONP (see What is JSONP, and why was it created? for more information on that).

Note that JSONP is a dirty and dangerous hack to work around the Same Origin Policy and that we now have CORS (which is a well-standardised and flexible means to selectively disable the Same Origin Policy that doesn't have JSONPs drawbacks). So don't go with option 2.


You might have tried using dataType: "jsonp" because you got an error like:

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

This error occurs because you are violating the Same Origin Policy. JSONP is one way to work around it, CORS is a better way. Both of those ways require the server to be changed to allow them to work.

See this question for more information.

As you are sending the jsonp request, you need to change how you are returning data. you need to wrap your JSON object in $_GET['callback']. if your backend was in php you can try the following code

 $response['data'] = array('sdu');
 $response = json_encode($response);
 echo htmlspecialchars($_GET['callback']) . '(' . $response . ')';
 exit;