javascript
  • web-services
  • 2012-02-13 136 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

    相关问题