2017-08-05 121 views
0

我正在关注newboston ajax教程,但遇到了错误。 我已经给出了错误的快照。我正在使用wamp服务器并在Chrome浏览器上运行它。Uncaught TypeError:无法读取属性'documentElement'的null message = xmlHttp.responseXML.documentElement.firstChild.data;

任何人都可以帮助我吗?

Error

Rendered HTML

的index.html

<!DOCTYPE html> 
      <html> 
      <head> 
        <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
        <meta content="utf=8" http-equiv="encoding"> 
        <script type="text/javascript" src="food.js"></script> 
      </head> 
       <body onload="process()"> 
        <h2>....Food Shop...</h2> 
        <input type="text" id="userinput" placeholder="enter the food u want" value="banana"> 
        <div id="underinput" /> 
       </body> 
      </html> 

food.js

var xmlHttp= createXmlHttpRequestObject(); 

function createXmlHttpRequestObject(){ 

    var xmlHttp; 

    if(window.ActiveXObjects){ 
     try{ 
      xmlHttp= new ActiveXObject("Microsoft.XMLHTTP"); 

     } 
     catch(e) 
     { 
      xmlHttp = false; 
     } 
    } 
    else 
    { 
     try{ 
       xmlHttp= new XMLHttpRequest(); 
     }catch(e) 
     { 
       xmlHttp=false; 
     } 
    } 

    if(!xmlHttp) 
    { 
    alert("cant create the object"); 
    } 
    else{ 
     return xmlHttp; 
    } 
} 


function process(){ 
    if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){ 
     food=encodeURIComponent(document.getElementById("userinput").value); 
     xmlHttp.open("GET","foodstore.php?food=" + food,true); 
     xmlHttp.onreadystatechange= handleServerResponse; 
     xmlHttp.send(null); 


    }else{ 
     setTimeout('process()',1000); 


    } 
} 
function handleServerResponse(){ 
    if(xmlHttp.readyState == 4){ 
     if(xmlHttp.status == 200){ 


      message = xmlHttp.responseXML.documentElement.firstChild.data; 
      document.getElementById("underinput").innerHTML= '<span style="color:blue">' + message + '</span>'; 
      setTimeout('process()',1000); 
     }else{ 
      alert('something wrong...'); 
     } 
    } 
} 

foodstore.php

<?php 
    error_reporting(E_ALL); 
    int_set('display_errors',true) 
    header('Content-Type: text/xml'); 
    echo '<?xml version="1.0" encoding="UTF=8" standalone="yes" ?>'; 
    echo '<response>'; 
     $food = $_GET['food']; 
     $foodArray= array('banana','apple','mango'); 
     if(in_array($food,$foodArray)){ 
      echo 'we do have'.$food; 
     } 
     else if($food ==''){ 
      echo 'enter the food'; 
     } 
     else{ 
      echo 'sorry we do not have'.$food; 
      } 
    echo '</response>'; 
?> 
+1

它告诉你'xmlHttp.responseXML'为空,所以你应该日志,看看服务器返回真的你 – adeneo

+0

可以请告诉我如何登录 – Dharmesh

+0

'的console.log(xmlHttp.responseXML) '和'console.log(typeof xmlHttp.responseXML)' – adeneo

回答

0

我相信这个错误在于生成XML数据的PHP代码。当我尝试使用该代码时,我尝试使用JavaScript分析xml时出现错误。我得到的错误是:

This page contains the following errors:error on line 1 at column 34: String not closed expecting " or ' Below is a rendering of the page up to the first error.

当您使用PHP来产生为什么不使用正确的方法是PHP核心的一部分,XML - 即DOMDocument

以下是您的代码的修改版本,应返回您正在处理的响应。

<?php 
    if($_SERVER['REQUEST_METHOD']=='GET' && !empty($_GET['food'])){ 

     /* Filter the input data */ 
     $food = filter_input(INPUT_GET, 'food', FILTER_SANITIZE_STRING); 

     /* an array of foodstuffs */ 
     $foods = array('banana','apple','mango','orange','plum','peach','cherry','kiwi','grape','lemon'); 

     /* Construct the response message based upon existance of food */ 
     $message = empty($food) ? 'enter the food' : (in_array($food, $foods) ? 'We do have '.$food : 'Sorry, we do not have '.$food); 


     /* using DOMDocument to output a correctly formed XML document */ 
     $dom=new DOMDocument('1.0', 'utf-8'); 
     $dom->appendChild($dom->createElement('response', $message)); 
     $xml = $dom->saveXML(); 
     $dom=null; 


     /* send the response */ 
     header('Content-Type: application/xml'); 
     exit($xml); 
    } 
?> 
<!doctype html> 
<html> 
    <head> 
     <title>Ajax and XML</title> 
     <script> 
      /* lightweight utility function for making ajax requests */ 
      function ajax(url,method,params,callback){ 
       var xhr=new XMLHttpRequest(); 
       xhr.onload=function(){ 
        callback.call(this, this.response) 
       }; 
       xhr.onerror=function(e){ 
        console.log(e) 
       }; 
       var payload=[]; 
       for(var n in params)payload.push(n + '=' + params[ n ]); 
       var p; 

       switch(method.toLowerCase()){ 
        case 'post': p=payload.join('&'); break; 
        case 'get': url+='?'+payload.join('&'); p=null; break; 
       } 
       xhr.open(method.toUpperCase(), url, true); 
       xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
       xhr.send(p); 
      } 

      /* utility function to get a parser to process XML data */ 
      function get_parser(str_xml) { 
       try { 
        if(window.XMLSerializer && typeof(DOMParser)!='undefined') { 
         var parser = new DOMParser(); 
         return parser.parseFromString(str_xml, 'application/xml'); 

        } else if(typeof(ActiveXObject) != 'undefined') { 
         var parser = CreateMSXMLDocumentObject(); 
          parser.async='false'; 
          parser.load(str_xml); 
         return parser; 

        } else { 
         var url = 'data:text/xml;charset=utf-8,' + encodeURIComponent(str_xml); 
         var request = new XMLHttpRequest(); 
          request.open('GET', url, false); 
          request.send(null); 
         return request.responseXML; 

        } 
       } catch(err) { 
        console.warn(err); 
       } 
      } 

      function process(){ 
       /* 
        Change to suit your environment ~ for this demo I use same page (location.href) 
       */ 
       var food = document.querySelector('input[name="food"]').value; 
       if(food && food!=''){ 
        //ajax.call(this, 'foodstore.php', 'get', { food:food }, handleServerResponse); 

        ajax.call(this, location.href, 'get', { food:food }, handleServerResponse); 
       } 
      } 

      /* callback function to process xml response data */ 
      function handleServerResponse(response){ 
       if(response){ 

        /* parse xml response */ 
        var xml=get_parser(response); 

        /* get the node which is of interest - only one in this case */ 
        var message = xml.documentElement.textContent; 

        /* output message to browser */ 
        document.getElementById("underinput").innerHTML= '<span style="color:blue">' + message + '</span>'; 
       } 
      } 


      function bindEvents(e){ 
       document.getElementById('bttn').onclick=process; 
      } 
      document.addEventListener('DOMContentLoaded', bindEvents,{ passive:true, capture:false }); 
     </script> 
    </head> 
    <body> 
     <form name='geronimo'> 
      <label for='food'>Enter Food<input type='text' name='food' placeholder='eg: apple' size=60 /></label> 
      <input type='button' id='bttn' value='Check' /> 
      <div id='underinput'></div> 
     </form> 
    </body> 
</html> 
相关问题