weixin_33721427 2019-03-19 11:35 采纳率: 0%
浏览 20

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>
  • 写回答

2条回答 默认 最新

  • from.. 2019-03-19 11:46
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)