简体   繁体   中英

$.get Callback function not executed

I executed the following simple program expecting the callback function of get method will execute. But it only make the AJAX call and callback function is not executed. 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:

 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

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.


Change the server side code so it reports the correct content-type (probably text/plain ) or encodes the data as 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.

 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>

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