使用ajax和javascript

时间:2016-03-28 20:28:47

标签: javascript php ajax

尝试从php服务器获取数据。数据显示文件本身。控制台中没有显示错误。

function process() {
 if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) { // 0 and 4 if object is ready to go and not busy
    food = encodeURIComponent(document.getElementById("userInput").value); //document is web page
    //        to communicate with server
    xmlHttp.open("GET", "foodstore.php?food=" + food, true); //create we wana sent to server, request type should be same, uri is second parameter, true is request to be handled asynchrously
    xmlHttp.onreadystatechange = handleServerResponse; //3.handle that request,like update a page or something
    xmlHttp.send(); //if GET then null
 } else {
    setTimeout(process, 1000);
    //if busy timeout then communicate again
 }
}

foodstore.php

在foodItems中使用数组并检查输入框中是否输入了字母。

<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'; 
//response stored in food 
echo '<response>'; 
    $food = $_GET['food'];
    $foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food, $foodArray)) 
        echo 'We do have' .$food.'!' 
    elseif($food=='') 
        echo 'Enter a food ass';
else 
        echo 'Sorry we dont sell no ' .$food.'!'; 
echo '</response>'; 
?>

1 个答案:

答案 0 :(得分:0)

如果正在显示文本并且它与您列出的代码相同,那么这意味着运行它的服务器不会将其视为php脚本,即它认为它是纯文本或其他内容。看看这里可能的原因......

Apache shows php code instead of executing