简体   繁体   中英

jquery .ajax call does not execute the success function

Below is the jquery code to call a json web service.

    function getMajorGroups(){

    var element = $(".item-group-button");
    var response = $.ajax({
        type:"GET",
        url:"http://localhost:6458/posApplication/touch/getAllMajorGroupsForTouch",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data:{}
    });

    response.done(function(data){
        alert(data);
    });

    response.fail(function() {
        $("#item-groups").empty();
    });
}

I connect to a service in my localhost and the URL is as given above! When I remove the http:// the response.fail only runs. when I add the http:// both success or fail doesn't run. Is this method I've written is wrong or is there anything missing. I'm calling a JSON Web service here!

The webservice returns a JSON string when I try it in the browser! I'm calling a GET type service method.

Update :

this is the Json response when I directly use the URL in the browser.

{"majorGroups":[{"update":"false","hasMore":"false","status":"A","description":"Beverage","majorGroupId":"48","code":"Beverage"},{"update":"false","hasMore":"false","status":"A","description":"Laundry","majorGroupId":"51","code":"Laundry"},{"update":"false","hasMore":"false","status":"A","description":"Cigarette","majorGroupId":"50","code":"Cigarette"},{"update":"false","hasMore":"false","status":"A","description":"Food","majorGroupId":"47","code":"Food"},{"update":"false","hasMore":"false","status":"A","description":"Health Center","majorGroupId":"52","code":"Health Center"}],"failure":"false"}

While using dataType=json there is one probable issue which cause failure:

As per http://api.jquery.com/jQuery.ajax/

json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead.

Another approach you could take is to use .getJSON function, see http://api.jquery.com/jQuery.getJSON/ Again take a note of (from .getJSON doc):

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently...

On Firefox, add FireBug plugin and check Network tab.

I had the same problem. In my case the was caused because I was using a "date" from MySQL and something gets corrupted. I just needed to previously format that field and thats was it.

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