dongshi9407 2015-08-28 06:58
浏览 330

request.responseText接收正确的数据,但JavaScript无法理解

I am new to AJAX and presently learning it from Head First AJAX. The problem I am facing is really weird. I developed a simple program that creates a request through JavaScript and then shows the output.

main.js

window.onload = initPage;
function initPage() {
    request = createRequest();
    if(request == null) {
        alert("request could not be created");
    }
    else {
        var url = "requestMe.php";
        request.onreadystatechange = showResult;
        request.open("GET", url, true);
        request.send(null);
    }
 }

function showResult() {
    if(request.readyState == 4) {
        if(request.status == 200) {
            if(request.responseText == "okay") {
                alert("A successful request was returned");
            }
            else {
                alert("ALERT : " + request.responseText);
            }
         }
         else {
            alert("Request status received was not correct");
         }
    }
}

//--function to create request objects--
function createRequest(){
   try{
       request = new XMLHttpRequest();
   }
   catch(tryMS){
       try{
           request = new ActiveXObject("Msxm12.XMLHTTP");
       }
       catch(otherMS){
           try{
               request = new ActiveXObject("Microsoft.XMLHTTP");
           }
           catch(failed){
               request = null;
           }
       }
    }
    return request;
}

Now, here is the php script.

requestMe.php

<?php
   echo 'okay';
?>

This code should give the alert A successful request was returned

But instead it gives the result ALERT : okay

The weird thing is this same code was working yesterday for me when I tried it and now it is giving me this result. I tried to create similar programs and they all are showing me this kind of weird behavior. The responseText received is correct because it appends okay after ALERT :. What wrong am I doing here in the code? Why is it going to the else part when the responseText received is correct?

Any Help? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dsj0312 2015-08-28 07:13
    关注

    Do one thing add exit; after echo 'okay';

    Issue in your code is after ?> there is extra space available you can fix it either by removing ?> or removing extra space after ?>.

    I hope it will fix your issue.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测