带有 JavaScript 异常的 ajax:意外的输入结束


ajax with JavaScript exception: unexpected end of input

我有一个概念的输入字段,当用户填写它时,他必须检查这个概念是否存在。所以我做了一个检查按钮,它使用 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:检查数据库的函数,我总是在其中返回true

public function isExistedConcept($concpetName,$Ajax){
        if($Ajax==true){
            $results=true
             $d=array($results);
            return json_encode($d);
        }
 }

演示:http://jsfiddle.net/Wiliam_Kinaan/s7Srx/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;
 }

试试这个:

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),看看您是否得到了除应该存在的内容之外的其他内容。

试试这个:

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);