我有一个概念的输入字段,当用户填写它时,他必须检查概念是否存在。所以我创建了一个检查按钮,它使用ajax和JavaScript检查数据库以查看该概念是否存在。我的问题是当使用ajax和JavaScript时我得到了这个例外:
意外的输入结束
JS:
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
}
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.send();
什么是例外,我该如何解决?
PHP:检查数据库的功能,我总是在其中返回
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
return json_encode($d);
}
}
答案 0 :(得分:2)
在查看代码一段时间之后,可能有一件事可能是你的PHP。
你在php中的函数以return
命令结束。 AJAX调用实际上正在等待的是一些要发回的数据。 return命令只是将该值传递回最初调用该函数的实体。
尝试将您的函数更改为echo
结果而不是返回结果。保存返回值,以便在需要结果进入另一个PHP函数时,而不是在将数据返回给客户端时
我只是把这个返回命令放在这里以便于阅读。
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
echo json_encode($d);
}
return;
}
答案 1 :(得分:0)
试试这个:
public function isExistedConcept($concpetName,$Ajax) {
if( $Ajax) return "1";
}
// This is a simplified version of what you're doing, but it returns "1" instead of "[true]"
// Now for the JS:
if( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var isexisted = xmlhttp.responseText == "1";
if( isexisted) {...}
如果这不起作用,请尝试添加alert(xmlhttp.responseText)
并查看您是否获得了除此之外的任何内容。
答案 2 :(得分:0)
试试这个:
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
else{
console.log('error');
}
}
}
}
xmlhttp.send(null);