Ajax请求总是引发错误

时间:2012-10-08 14:28:29

标签: javascript ajax

function loaded() {
    var xmldoc,
    currenttime = new Date().getTime(),
    req,
    address = 'http://webservices.foo.com/eSignalQuotes/eSignalQuotes.asmx/GetDelayedQuotes?',
    symbols = 'symbols=' + '+c,s,ct,zw,kw,adm+', 
    cusip = '&cusip=',
    fields = '&fields=' + 'desc,month,year,recent,netchg,-decimal',
    type = '&type=' + 'future,stock,index',
    dispfullname = '&dispfullname=' + 'true',
    datefmt = '&datefmt=',
    timefmt = '&timefmt=',
    timestamp = '&' + Math.floor(currenttime/3600000),
    query = address + symbols + cusip + fields + type + dispfullname + datefmt + timefmt + timestamp;
    ;

    if(window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    req.addEventListener('error', function(e) {alert('Error');}, false);
    req.addEventListener('load', function(e) {xmldoc = req.responseText;}, false);
    req.open('GET', query, true);
    req.send();

}

这就是我的代码的样子,它总是在Safari和Firefox中引发错误。疯狂的是,如果我删除事件侦听器,并将响应类型更改为responseText,Internet Explorer会给我输出。我试过overrideMimetype,但这似乎没有帮助。如果我在Firefox或Safari中检查响应,我会得到null。我很茫然,任何帮助都会受到赞赏。

我应该提一下,我宁愿避免使用任何第三方库。

更新: 在progress事件期间发生错误,如果我检查.lengthComputable,我会false

更新2: Safari在这个问题上有了更多的启示:

XMLHttpRequest cannot load Origin is not allowed by Access-Control-Allow-Origin.

1 个答案:

答案 0 :(得分:0)

我不能百分百肯定,但在我看来,这个问题涉及跨站点沟通。我最终做的是让PHP脚本下载文件,然后我使用javascript在本地获取它。

<?php
    $mark = $_GET['mark'];
    $xmldoc = new DOMDocument();
    $xmldoc -> preserveWhiteSpace = false;
    $xmldoc -> formatOutput = true;
    $xmldoc -> load($mark);
    unlink('fenced.xml');   
    echo $xmldoc -> save('fenced.xml');
?>

使用Javascript:

localreq.open('GET', 'fenced.xml', true);
localreq.addEventListener('load', function(e) {xmldoc = localreq.responseXML;}, false);
localreq.send();