简体   繁体   中英

Using $.ajax to return HTML & turn it into JavaScript array

var urlArray = window.location.pathname.split("/"),
    idFromUrl = urlArray[2],
    dataPath = "/bulletins/" + idFromUrl + "/data";

$.ajax({
    url: dataPath,
    type: "get",
    dataType: "html",
    success: function (data) {
        var dataObj = data.replace(/"/g, '"');

        console.log(dataObj);
    }
});

I'm grabbing the contents of an HTML page, and the contents on that page is super simple. It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. This is all that's on that HTML page:

[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]

Without replace the " 's, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]

So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array?

您可以使用JSON.parse

JSON.parse(dataObj);

Change "dataType" to "json" and it will convert it for you:

var urlArray = window.location.pathname.split("/"),
    idFromUrl = urlArray[2],
    dataPath = "/bulletins/" + idFromUrl + "/data";

$.ajax({
    url: dataPath,
    type: "get",
    dataType: "json",
    success: function (data) {
        console.log(data);
    }
});

If it is returning the " instead of " , then I would change the AJAX return page to make sure it is doing a proper JSON response.

您可以将返回的HTML片段解析为JSON:

JSON.parse(dataObj);

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