Javascript web服务请求不起作用

Javascript web service request not working

本文关键字:不起作用 请求 服务 web Javascript      更新时间:2023-09-26

我有一个可以工作的PHP web服务,它可以返回数据(如果我将url输入到浏览器中,我就会得到结果)。我需要使用Javascript从我的web服务中检索这些数据,但我对Javascript不是很在行。根据我读过的所有教程、示例和StackOverflow问题和答案,这应该有效,但它没有。请帮忙!

<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>

我知道这并不能直接回答您的问题,但如果您对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");



要回答您的第二个问题(在注释中),代码看起来是正确的,但可能您得到了不好的答复。您可以将additions事件附加到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"); });