How to process json response from ajax call

2019-03-02 16:35发布

My webservice returns a JSON object like following

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

i.e. 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 ;
}

1条回答
小情绪 Triste *
2楼-- · 2019-03-02 17:26

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, e.g.

callback([1, 2, 3])

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

Access-Control-Allow-Origin: *
查看更多
登录 后发表回答