简体   繁体   中英

How to process json response from ajax call

My webservice returns a JSON object like following

["abc","xyz","option_3"]

ie when I put this address in chrome browser http://localhost:8088/rest/getOptions I get above.

I am trying to read this in browser so that I can create a drop-down option... but I get nothing from below code to start with:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        url="http://localhost:8088/rest/getOptions";
        var ajaxResult = null;
        function getData(yt_url){
            $.ajax
            ({
                type: "GET",
                url: yt_url,
                dataType:"json",
                async: false,
                success: function(response){
                    ajaxResult = response;
                }
            });
        }
        getData(url);

    alert(ajaxResult);

    </script>
</head>
<body>
</body>
</html>

I always get null in alert box. I double checked with fiddler2 that webservice request/response is going through fine, I even can intercept json object between webservice and the browser.

I also tried

var obj = JSON.parse(ajaxResult);
alert(obj);

I get null again.

I have already looked at Ajax call for the json response and similar questions. Please see my JSON is a bit different, so either those solution won't apply in my case or I didn't follow them.

I am a new to AJAX and Java script, please advise.

EDIT: addding JERSEY webservice code which serves this rest/getOptions end point

@GET
@Path("getOptions")
@Produces(MediaType.APPLICATION_JSON)
public List<String> getOptionsJson() {
    //build alloptions List<String>
    return alloptions ;
}

Update

You edited the question; you can't use dataType: 'json' because of cross-domain issues that can only be overcome by either using a proxy on the same domain or via CORS .

When you use dataType: 'jsonp' you can't use async: false ; this is because it doesn't really use XMLHttpRequest but uses the <script> tag to make it do cross-domain. I believe jQuery simply ignores the async setting without issuing a warning.

Therefore, the alert() will always be empty and you should move it inside the success callback.

To support JSONP your web service must wrap the returned data into a function call, identified by the callback GET parameter, eg

callback([1, 2, 3])

If your web service doesn't support this, as mentioned before, you would need to use CORS , eg add this response header:

Access-Control-Allow-Origin: *

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