JQuery.ajax () request fails

I am trying to make an AJAX call on my web server to pull city information.

  • I have a selection on the page filled with three values: [blank], "New York, NY" and "Ann Arbor, MI"
  • When an item is selected, the city name is reformatted: spaces turn to '-'
  • Then .ajax() runs "/ data / [city]"
  • When the server responds, it calls alert() with the restored JSON object.

The code:

 $( document ).ready(function() { $('#city').change(function () { var city = $.trim($(this).val()).replace(/ /g,"-"); if(city.length > 0) { var url = "/data/cities/" + city; $.ajax({ url: url, context: document.body, dataType: 'json' }).done(function(data) { alert(data); }); } }); }); 

For some reason, calling .ajax() does not work. An outgoing HTTP request is never executed if the url is:

  • /data/cities/New-York,-NY

However, it fires successfully when url is:

  • /data/cities/New-York-NY (without a comma)
  • /data/cities/New-York,NY (no dash)
  • /data/cities/New-York,-NYC (optional character)
  • /data/cities/Ann-Arbor,-MI (similar format)

I checked:

  • The browser does not execute an outgoing HTTP request when it "does not work" (as indicated on the Chromium Network tab).
  • The web server receives HTTP requests for all URLs except this problem
  • There are no Javascript errors on the page.

Am I missing something obvious? It seems really strange that .ajax() does not run this particular url ...

EDIT:

Added error callback to .ajax() request. It does not work with the error state = "reject" and statusText = "error".

As requested, the <select> on the page:

 <select id="city"> <option value=""></option> <option value="New York, NY">New York, NY</option> <option value="Ann Arbor, MI">Ann Arbor, MI</option> </select> 
+4
source share
1 answer

By default, if you have not used $ .ajaxSetup for default settings that you do not show us, you use the GET method. Since you do not specify an explicit value for the cache, and its default value is true according to the jquery specification (api.jquery.com/jQuery.ajax), your browser may work with an earlier (cached) response (even if the source code, which you see in the browser, updated). I would suggest using POST (if you and if the server allows it) and / or specify a cache: false explication in the call to $ .ajax ({...}), just to release any funny things.

(copy / paste from my comment as requested about this question)

+4
source

Source: https://habr.com/ru/post/1495141/


All Articles