我正在嘗試一個基本的AJAX/PHP測試。我有一個帶有兩個輸入文本字段的表單,其中輸入兩個值和一個輸出文本字段,當我按下按鈕時,輸入字段連接在一起並輸出到第三個文本字段。我通過AJAX/PHP來做到這一點。我將連接值輸出到第三個字段,但似乎還有一些額外的文本附加到我從PHP返回的responseText上。附加的文本是帶有Web服務器主機名和時間戳的HTML註釋(< - )。我如何擺脫這一點?這是正常的responseText回來與這個額外的信息在responseText字符串?爲什麼responseText將主機名和時間戳附加到它?
的PHP/HTML頁面如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX/PHP Test</title>
</head>
<body>
<script language="javascript" type="text/javascript">
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Change the value of the output field
function setOutput() {
var val;
val="";
if (httpObject.readyState == 4) {
val=httpObject.responseText;
if (val != undefined) {
document.getElementById('outputFld').value = val;
}
}
}
// Implement business logic
function doWork(){
var url;
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.onreadystatechange = setOutput;
url="concat.php?inputText="+document.getElementById('inputFld1').value+"&inputText2="+document.getElementById('inputFld2').value;
httpObject.open("GET", url, true);
httpObject.send(null);
}
}
var httpObject = null;
</script>
This is a test page to see how to get ajax and php to work together when submitting a form with data.
<P>
First we have a simple form. The php will be called when the button is pressed and will concatenate
"Input 1" and "Input 2" and write the output to the "Output" field. <P><P>
</body>
<form>
Input 1: <input type="text" id="inputFld1" size="50" /><br>
Input 2: <input type="text" id="inputFld2" size="50" /><br>
<HR>
Output: <input type="text" id="outputFld" size="100" /><br>
<P>
<input type="button" name="submitButton" value="Concatenate" onClick="doWork()" />
</html>
和PHP被稱爲與OPEN調用(concat.php)的網址如下:
<?php
$in1 = $_GET['inputText'];
$in2 = $_GET['inputText2'];
$returnvar = $in1 . ' - ' . $in2;
echo $returnvar;
?>
得到什麼(如果我的兩個輸入字段中包含「ONE」和「TWO」字樣:
ONE - TWO<!-- webserver1.thedomain.com compressed/chunked Thu Jul 1 15:42:08 PDT 2010 -->
什麼是「評論附加到responseText?
我想你可能是對的。我們可能在這裏爲PHP或apache設置了特殊的設置。 – GregH 2010-07-01 22:48:03
至於你的問題「我該如何擺脫它?」: 如果你只是添加到頁面的東西作爲HTML,無論如何評論,否則一些JS「評論刪除」正則表達式的魔術可能會幫助: http:///www.w3schools.com/jsref/jsref_obj_regexp.asp – 2010-07-01 22:55:04