简体   繁体   English

$.get 回调 function 未执行

[英]$.get Callback function not executed

I executed the following simple program expecting the callback function of get method will execute.我执行了下面的简单程序,期望 get 方法的回调 function 将执行。 But it only make the AJAX call and callback function is not executed.但它只会使 AJAX 调用和回调 function 不执行。 Due to this returned data is not showing in alert box.由于此返回的数据未显示在警报框中。 Appreciate your help.感谢你的帮助。 Thanks谢谢

 $(function() { $("#bt1").click(function() { url = "https://run.mocky.io/v3/5b0c30b2-1069-4640-9bb6-18ceb95c25c4"; $.get(url, function(data) { alert(data); }); }); });
 <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <div id="div1"> This is dummy data </div> <button id="bt1"> Click here </button>

Add a fail handler so you can see what errors jQuery reports:添加一个fail处理程序,以便您可以查看 jQuery 报告的错误:

 let url = "https://run.mocky.io/v3/5b0c30b2-1069-4640-9bb6-18ceb95c25c4"; $.get(url, function(data) { alert(data); }).fail(function(jqXHR, status, error) { console.log(`error: ${error}`) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

It says:它说:

error: SyntaxError: Unexpected token S in JSON at position 0错误:语法错误:JSON 中的意外令牌 S 在 position 0

The server is reporting:服务器报告:

 Content-Type: application/json; charset=UTF-8

but the body:但身体:

 Sun Jan 3 18:05:31 IST 2021

… isn't JSON. … 不是 JSON。


Change the server side code so it reports the correct content-type (probably text/plain ) or encodes the data as JSON .更改服务器端代码,使其报告正确的内容类型(可能是text/plain )或将数据编码为 JSON


For the sake of completeness, I'll mention that you can tell jQuery to override the Content-Type with the parameter after the success function, but that is hacking around the problem instead of fixing the cause so I don't recommend it.为了完整起见,我会提到您可以告诉 jQuery 在成功 function 后使用参数覆盖Content-Type ,但这是解决问题而不是解决问题,所以我不推荐它。

 let url = "https://run.mocky.io/v3/5b0c30b2-1069-4640-9bb6-18ceb95c25c4"; $.get(url, function(data) { alert(data); }, "text").fail(function(jqXHR, status, error) { console.log(`error: ${error}`) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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