简体   繁体   中英

AJAX get request sometimes fails on iOS Safari

I'm trying to display a json feed I created onto another page in my site using jQuery AJAX. For the most part, I've got it working perfectly using the following code, except on iOS Safari it occasionally doesn't work (about 1 in 10). When I say it doesn't work, nothing is appended to the document, and my '.items' element is left empty.

Here is my jquery script, which I run on window load:

$.ajax({
    type: "GET",
    url : '/json',
    success: function (data) {
        var json = JSON.parse(data.replace(/"/g, '"'));
        $.each(json.data, function (index, element) {
            $(".items").append("<p>" + json.data[index].Title + "</p>");
        });
     }
});

Here is the JSON feed, which seems to be valid, but when adding dataType:'json' to my ajax request, nothing is returned:

{
    "data": 
    {
        "1": {
            "Title": "Page 1",
            "Url": "/page-1"
        },

        "2": {
            "Title": "Page 2",
            "Url": "/page-2"
        },

        "3": {
            "Title": "Page 3",
            "Url": "/page-3"
        }
    }
}

Weirdly, no error messages are ever displayed when this doesn't work, so I have no idea what the actual cause is. My suspicions are that either the JSON isn't formatted properly, or the JSON isn't getting parsed for whatever reason. On desktop browsers it always works, so this leads me to believe these aren't the causes, and that maybe it's just a iOS bug.

Can anyone help me out with this issue? Is there a way to check if my json has parsed correctly?

I had the exact same issue where iOS Safari would return "" even for a static valid JSON file... so I looked for anything similar between our code and since we're both using "GET", I decided to try POST, because why not... and sure enough, POST always return my json through ajax where GET didn't...

It's definitely something in iOS safari not handling it correctly, but switching to POST worked for me... just in case someone else is running into the same issues out there.

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