javascript
  • web-services
  • 2012-02-13 106 views 0 likes 
    0

    我有一個可用的PHP web服務返回數據(如果我將url輸入到瀏覽器中,我會得到結果)。我需要使用Javascript從我的Web服務中檢索這些數據,但我不太喜歡使用Javascript。基於所有的教程,示例和StackOverflow問題和答案,我讀過這個應該可以工作,但事實並非如此。請幫忙!Javascript web服務請求不起作用

    <script type="text/javascript"> 
    
    var url = '*working url*'; 
    var xmlhttp = null; 
    if (window.XMLHttpRequest) { 
        xmlhttp = new XMLHttpRequest(); 
    } 
    else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
    else { document.write('Perhaps your browser does not support xmlhttprequests?'); } 
    
    xmlhttp.open('GET', url, true); 
    xmlhttp.send(null); 
    
    xmlhttp.onreadystatechange = function() { 
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
        var myObj = eval (xmlhttp.responseText); 
        } else { 
        // wait for the call to complete 
        } 
    }; 
    
    </script> 
    

    此外,我需要幫助確保我正確調用它。目前,我不喜歡這樣,這可能是問題:

    <script type="text/javascript"> 
    document.write(myObj); 
    </script> 
    
    +1

    使用jQuery ..... – dynamic 2012-02-13 01:12:32

    +0

    不使用文件.write – epascarello 2012-02-13 01:13:52

    回答

    1

    我知道這並不直接回答你的問題,但如果你是「不太大」使用javascript我會建議只是直接去jQuery而不是搞亂較低級別的對象。

    它還可以幫助您跨瀏覽器兼容性。

    http://jquery.com/
    http://api.jquery.com/category/ajax/

    但是,如果你在未來有一個特別無聊的日子一定的時間,回去和學習發生了什麼事情的幕後總是有益的。

    這將是使用jQuery一個簡單的Ajax後(用文本響應):

    $.post(
        "test.php", 
        { postValue1: "hello", 
         postValue2: "world!" }, 
        function(data){ 
         alert("Success: " + data); 
        }, 
        "text"); 
    



    要回答你的第二個問題(在評論),代碼看起來正確的,但也許你得到不好的迴應。您可以將附加事件附加到ajax調用以獲取更多信息。

    這段代碼是借來的,並從jQuery的網站修改:
    http://api.jquery.com/jQuery.post/

    我得到的功能參數信息來源:
    http://api.jquery.com/jQuery.ajax/

    // Assign handlers immediately after making the request, 
    // and remember the jqxhr object for this request 
    var jqxhr = $.post("example.php", function() { 
        alert("success"); 
    }) 
    .success(function(data, textStatus, jqXHR) { alert("second success"); }) 
    .error(function(jqXHR, textStatus, errorThrown) { alert("error"); }) 
    .complete(function(jqXHR, textStatus) { alert("complete"); }); 
    
    +0

    好的,所以如果我正在尋找使用jQuery獲取ajax,那麼從我看到的,以下應該工作: ' \t \t \t \t \t \t \t \t '我在這裏的問題是,我沒有得到任何數據返回。只有一個沒有文字的警告框。你能看到我在這裏做錯了嗎? – 2012-02-13 22:56:17

    +0

    沒關係我明白了。謝謝! – 2012-02-13 23:10:12

    +0

    對不起,以爲我標記了它,猜不到!儘管現在明白了 – 2012-02-15 20:23:00

    相關問題