我一直在学习在GET请求中使用AJAX,它允许我通过服务器上的一组数据访问PHP脚本。我希望能够发送一个请求,告诉服务器运行代码,这些代码将打开一个应用程序并处理这个应用程序的一些信息。如何使用AJAX与服务器通信并运行代码?
这里是我用来首先与服务器通信的代码,然后发送请求到服务器,并最终处理来自服务器的响应。
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("cant create that object hoss");
}
else
{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4) //State were object is free and ready to communicate with server
{
food = 'bacon';
xmlHttp.open("GET", "ExecuteMaya.php?food="+food,true); //Creates request that we are sending to server
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200) //Means communication was successful
{
var xmlResponse = xmlHttp.responseText;
var xmldom = (new DOMParser()).parseFromString(xmlResponse, 'text/xml');
var text = xmldom.getElementsByTagName("response")[0];
var message = text.childNodes[0].nodeValue;
foodTextOutput = message;
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}
这是我在学习如何使用AJAX时使用的PHP。当我将上述代码中的'xmldom'变量打印到控制台并检查它时,出现以下错误 - “第1行第2行错误:文档结尾处的额外内容”。这可能是我原来的帖子的一个不同的问题,但我想我会提出这个错误发生。这对于'var message = text.childNodes [0] .nodeValue;'这一行产生了敲门效应这产生了错误 - “Uncaught TypeError:无法读取未定义的属性'childNodes'”。
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>':
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 you idiot';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
,我一直在努力学习AJAX可能不相关的代码,我只是想我会发布它的情况下,我可以使用一些这方面的代码已经被写入的。总之,我希望能够发送一个布尔值,或者任何可以用AJAX生存的东西给服务器,告诉它运行一个脚本。然后,该脚本将打开一个Maya应用程序并运行我编写的一些Python代码。
预先感谢您!
所以 - 什么是问题,问题在哪里? – Jeff
@Jeff我不知道如何与服务器通信,以便我可以告诉它运行代码。另外如果有人能告诉我为什么我说的错误正在发生。谢谢。 – skelto
只要你通过ajax调用一个php脚本(就像你已经做过的那样),它就运行代码! – Jeff