Jquery AJAX XML数据返回语法错误

时间:2015-08-17 13:52:30

标签: jquery ajax xml xmlhttprequest

我遇到如下问题:

var number = 9876543.2109;
document.write(number.toLocaleString('en-US', { maximumFractionDigits: 2 }));
document.write('<br>');
document.write(number.toLocaleString('de-DE', { maximumFractionDigits: 2 }));

在上面的代码中,以xml标记开头的行返回语法错误,如下所示:       未捕获的SyntaxError:意外的标记ILLEGAL 这里有什么问题?

2 个答案:

答案 0 :(得分:1)

问题在于数据。这是一个非常长的字符串文字。如果您的字符串跨越多行,则可以使用"first line part" +\n "second line part" +\n..First line part\\n Second line part\\n .....。试试这个:

        data : "<?xml version=\"1.0\"?>\
                    <mainbody>\
                        <header>\
                            <company>companyName</company>\
                            <usercode>323423</usercode>\
                            <password>543543543</password>\
                            <startdate>010120150100</startdate>\
                            <stopdate>170820150100</stopdate>\
                            <type>1</type>\
                        </header>\
                    </mainbody>\
                ",

参考:Creating multiline strings in JavaScript

答案 1 :(得分:1)

您在变量中使用新行。试试这段代码:

<script>
$(document).ready(function(){
    $.ajax({
        url: "https://api.domain.com/message.asp",
        type: "POST",
        cache: false,
        contentType: "text/xml",
        dataType: "text",  
        data : "<?xml version=\"1.0\"?>\
                    <mainbody>\
                        <header>\
                            <company>companyName</company>\
                            <usercode>323423</usercode>\
                            <password>543543543</password>\
                            <startdate>010120150100</startdate>\
                            <stopdate>170820150100</stopdate>\
                            <type>1</type>\
                        </header>\
                    </mainbody>\
                ",
        crossDomain:true,
        success: function(result){
            alert(result);
        },
        error: function(result) {
          console.log(result);
        }
    });
});
</script>

虽然我认为这样写的数据会更清晰:

xml = "<?xml version=\"1.0\"?>"
    + "<mainbody>"
    + "    <header>"
    + "        <company>companyName</company>"
    + "        <usercode>323423</usercode>"
    + "        <password>543543543</password>"
    + "        <startdate>010120150100</startdate>"
    + "        <stopdate>170820150100</stopdate>"
    + "        <type>1</type>"
    + "    </header>"
    + "</mainbody>";

然后使用变量xml作为data - 属性。