简体   繁体   中英

$.ajax only working in Safari - probably something with request

the following script seems to work only in Safari

function getPictures() {
    $.ajax({
            type: "GET",
            url: "getimages.php",
            dataType: "xml",
            success: function(xml) {
                alert('success');
            }

    });
}

getimages.php dynamically creates xml content via PHP.

I read that this problem might have something to do with needing a request. I've never worked with Ajax in any way and don't have time to do research.

How do I have to change this script so it works in as many browsers as possible?

The XML output of the PHP file looks like this

    <image url="MY_IMAGE_URL_1.jpg" number="1">
    <image url="MY_IMAGE_URL_2.jpg" number="2">
    <image url="MY_IMAGE_URL_3.jpg" number="3">
    <image url="MY_IMAGE_URL_4.jpg" number="4">

etc.

I would have thought the success function will be called when the file is loaded regardless of it's content

Your XML is malformed.

Add / to close the tags.

<image url="MY_IMAGE_URL_1.jpg" number="1" />
<image url="MY_IMAGE_URL_2.jpg" number="2" />
<image url="MY_IMAGE_URL_3.jpg" number="3" />
<image url="MY_IMAGE_URL_4.jpg" number="4" />

First you should add an error event handler in your AJAX request:

function getPictures() {
    $.ajax({
        type: "GET",
        url: "getimages.php",
        dataType: "xml",
        success: function(xml) {
            alert('success');
        },
        error: function(req, status) {
            alert(status);
        }
    });
}

Second, you need to close all the elements in your XML (ending them with /> ) as well as wrap them in a containing element as there can only be one root element in XML :

<images>
    <image url="MY_IMAGE_URL_1.jpg" number="1" />
    <image url="MY_IMAGE_URL_2.jpg" number="2" />
    <image url="MY_IMAGE_URL_3.jpg" number="3" />
    <image url="MY_IMAGE_URL_4.jpg" number="4" />
</images>

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