search
HomeBackend DevelopmentPHP Tutorial调试一个ajax要吐血了

写了一个英汉词典,具体流程:
1. 把本地文件按照{English: Chinese}的格式写入memcached服务器
2. 通过ajax提交英语单词,并返回中文释义

遇到的问题: 查询对应的单词,可以通过file_put_contents函数写入本地,证明查询到了相应的单词,在客户端,通过readyState属性可以依次看到返回1,2,3,4,但是在window.alert(type res)时显示未定义。

//这部分代码是OK的,用于读取并解析本地的txt格式词典<?php 	class Word{	private $query_en='#\w+\b#i';	private  $query_ch='#[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5},\)\.\( \w]*#u';	private $arr_word=array();	private  $recycle_num=100;	private  $fp=null;		public function __construct($fileName)	{		$this->fp=fopen($fileName,'r') or die('打开ciba失败');	}			public function readWord()	{			while(!feof($this->fp))			{				$word=fgets($this->fp);				$word=trim($word);				if($word=='') continue;								$en=$this->parseEn($word);				$ch=$this->parseCh($word);				$this->arr_word["$en"]=$ch;								/* $this->recycle_num--;				if($this->recycle_num==0) return; */										}	}	public function parseEn(&$word)	{		if(preg_match($this->query_en, $word, $en))		{			return $en[0];		}		else		{			echo "match english word failed<br />";		}	}	public function parseCh(&$word)	{		if(preg_match($this->query_ch, $word, $ch))		{			return $ch[0];		}		else		{			echo "match chinese failed<br />";		}	}		public  function getWord()	{		return $this->arr_word;	}		public function __destruct()	{		fclose($this->fp);	}}//$word=new Word('ciba.txt');//$word->readWord();//echo "<pre class="brush:php;toolbar:false">";//print_r($word->getWord());//echo "
";  */?>//这部分代码也是OK的,用于将词条写入memcached

mem=new Memcache(); $this->mem->connect("127.0.0.1", 11211) or die("connect memcached failed!!!
"); } public function __destruct() { $this->mem->close(); } public function addWord() { $word=new Word('ciba.txt'); $word->readWord(); $result=$word->getWord(); //echo count($result)."字符
"; //exit(); foreach($result as $en => $ch) { $this->mem->add($en, $ch, MEMCACHE_COMPRESSED, time()+10*24*3600) or die("添加词条失败". __LINE__ ."
"); } } public function setWord($en,$ch) { //控制器判断输入是否合法 $en=$this->filterWord($en); $en=$this->mem->get($en) or die("找不到词条 $en"); $this->mem->set($en, $ch, MEMCACHE_COMPRESSED, time()+31*24*3600) or die("添加词条$en失败"); } public function getWord($en) { //控制器判断输入是否合法 $en=$this->filterWord($en); $ch=$this->mem->get($en) or die("找不到词条 $en"); return $ch; } public function replaceWord($en,$ch) { //控制器判断输入是否合法 $en=$this->filterWord($en); $en=$this->mem->get($en) or die("找不到词条 $en"); $this->mem->replace($en, $ch, MEMCACHE_COMPRESSED, time()+31*24*3600) or die("替换词条$en失败"); } public function deleteWord($en) { //控制器判断输入是否合法 $en=$this->filterWord($en); $this->mem->delete($en,0) or die("删除词条$en失败"); } //过滤掉中文,包括空格的词组,长度大于20的词条 public function filterWord($en){ $en=trim($en); if(preg_match('#[\x{4e00}-\x{9fa5},\)\.\(]+#u', $en)) { //echo '暂时不支持中文查询
'; if(preg_match('#\b[a-z]+\b#i', $en, $res)) { if(strlen($res[0])>20) { //echo "字符过长
"; return strtolower(substr($res[0], 0,20)); } return strtolower($res[0]); } } else if(preg_match('#\s+#', $en)) { //$en=explode(' ', $en); //echo "含有空格
"; $res=null; if(preg_match('#[a-z]+#i', $en, $res)) { if(strlen($res[0])>20) { //echo "字符过长
"; return strtolower(substr($res[0], 0,20)); } return strtolower($res[0]); } } else if(preg_match('#[?_\+\?\*\^\$\#\%\&\/\\,\.!@=\`\'\"\"""]#',$en, $res)) { // //echo '含有非法字符
'; if(preg_match('#[a-z]+#i', $en, $res)) { if(strlen($res[0])>20) { echo "字符过长
"; return strtolower(substr($res[0], 0,20)); } return strtolower($res[0]); } } else if(strlen($en)>20) { //echo "字符过长
"; return strtolower(substr($en, 0,20)); } else  { return $en; } } public function flushAll() { $this->mem->flush(); } public function getTime() { if (function_exists("micro_time")) { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } else { return time(); } }}//$mem=new MemStore();//$mem->addWord();//$mem->flushAll();//$mem->replaceWord('abandon', 100000000);//$mem->deleteWord('abandon');//echo $mem->getWord('_*&^%abandon^%$#');//echo "ok"; ?>//下面这段代码也是OK的,根据客户端提交的英语单词,可以成功查询到对应的中文,并写入本地文件成功过getWord($en); $en=$mem->filterWord($en); $res="".$en."".$ch.""; file_put_contents('aword.txt', $res."\r\n",FILE_APPEND);//这里是OK的 echo $res; //echo '{'.$en.':'.$res.'}';}else{ file_put_contents('aword.txt', "receive NON data \r\n",FILE_APPEND);}?>//我估计问题出在下面这段代码,,但是就是找不出问题所在,一直显示undefined <script>function getXMLHttpRequest(){ var xmlhttp=null; if(window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHttp"); } else { xmlhttp=new XMLHttpRequest(); } return xmlhttp;}function query(){ var url="/ciba/process.php"; var data="?enword="+$('enWord').value+"&rand="+Math.random(); $('enWord').value=""; //var url+=data; //window.alert(url+data); xmlhttp=getXMLHttpRequest(); if (xmlhttp) { xmlhttp.open("get", url+data,true); xmlhttp.onreadystatechange=function() { //window.alert(xmlhttp.readyState); if (xmlhttp.readyState==4 && xmlhttp.status==200) { var res=xmlhttp.responseXML; window.alert(typeof $res);//这个位置一直显示undefined var en=res.getElementsByTagName("en")[0].childNodes[0].nodeValue; var ch=res.getElementsByTagName("ch")[0].childNodes[0].nodeValue; $("chWord").innerText= en+": 的中文意思是: "+ch; } } xmlhttp.send(null); } }function $(id){ return document.getElementById(id);}</script>



ajax调试要吐血了


回复讨论(解决方案)

var  res=xmlhttp.responseXML;
window.alert(typeof  $res);

一样吗?不一样当然不行

var  res=xmlhttp.responseXML;
window.alert(typeof  $res);

一样吗?不一样当然不行




哎。这么明显的错误硬是没照出来。。我用的写字本写的代码。。怎么找都找不到。。。zend studio for eclipse 在我的机器上跑步起来,,有什么轻量级,功能齐全,自动高亮,自动补全的IDE推荐吗?

sublime  or  notepad++

var  res=xmlhttp.responseXML;
window.alert(typeof  $res);

一样吗?不一样当然不行



//客户端做出如下修改 xmlhttp.onreadystatechange=function()		{			//window.alert(xmlhttp.readyState);			if (xmlhttp.readyState==4 && xmlhttp.status==200)			{				var res=xmlhttp.responseText;				res=eval("("+res+")");				window.alert(res);				//var en=res.getElementsByTagName("en")[0].childNodes[0].nodeValue;								//var ch=res.getElementsByTagName("ch")[0].childNodes[0].nodeValue;				//var en=$("enWord").value;				/var ch=res.en;				$("chWord").innerText= en+": 的中文意思是: "+ch;   			}		} //服务器这边改成用json传回数据,修改如下<?phpheader("content-type: plain/text; charset=utf-8");require_once "storeWord.php";if(!empty($_GET['enword'])){	$en=$_GET['enword'];			$mem=new MemStore();	$ch=$mem->getWord($en);	$en=$mem->filterWord($en);		$res="<res><en>$en</en><ch>$ch</ch></res>";	file_put_contents('aword.txt', $res."\r\n",FILE_APPEND);	//ob_start();	$res='{"'.$en.'":"'.$ch.'"}';	echo $res;}else{	file_put_contents('aword.txt', "receive NON data \r\n",FILE_APPEND);}

//可以收到数据,不过收到的是一个html网页,试图在ob缓存里把结果过滤出来,但最后还是一个空html+结果

我就不明白了这段HTML是拿来的.* ,而且结果是在后面,ob过滤就失效了

36行应为 ob_clean();

36行应为 ob_clean();



我明白为什么了,谢谢。 其实如果不用ob_clean(),在接受的时候采用innerHTML而不是innerText也是可以的。 3Q 
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools