简体   繁体   English

Javascript和PHP JSON异步请求错误

[英]Javascript and PHP JSON Asynchronous Request Error

I am always catching errors when sending an async request from my client-side javascript to my web-service php code. 从客户端javascript向我的web服务php代码发送异步请求时,我总是发现错误。 No guarantee that I used those terms correctly but I tried. 不能保证我正确使用这些条款,但我尝试过。 It always catches an error and I think that the php code is not even being called. 它总是捕获一个错误,我认为PHP代码甚至没有被调用。

function suggestSearch() {
     var value = document.getElementById("filterText").value; //Suchtext
     let reqObj = {method: "getNames", input: value};
     fetch("actions/async_search.php", {method:"POST",body:JSON.stringify(reqObj)})
      .then((response) => {
           if(response.ok) {
                let contentType = response.headers.get("content-type");
                if(contentType && contentType.indexOf("application/json") != -1) {
                     return response.json();
                }
            }
            throw new Error("Error in response!");
      })
      .then((result) => {
           for(var i = 0; i < result.length; i++) {
                 var obj = result[i];
                 console.log(obj.id);
           }
       })
       .catch( (error) => { alert("An error occured!" + error);
       })
}

async_search.php: async_search.php:

 header("Content-Type: application/json");
    $result = ["result" => null];

    $request = file_get_contents("php://input");

    if(isset($request) && !empty($request)) {
        $requestObj = json_decode($request);
        if($requestObj->method == "getNames") {
            $input = $requestObj->input;
            if($input != "") {
                $sql = "SELECT ArtikelName FROM artikel WHERE ArtikelName LIKE ? LIMIT 5;"; 
                $statement = $conn -> prepare($sql); //prepare
                $statement -> execute(array("$input%")); 
                $result = $statement -> fetchall(PDO::FETCH_ASSOC);
                echo json_encode($result);

            }
        }
    }

// EDIT : Now I came so far that I get this as an error: //编辑:现在我到目前为止,我得到这个错误:

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据第1行第1列的意外数据结尾

I have found the error. 我发现了错误。 When saving to the $result array I have to put the variables in brackets, eg 保存到$ result数组时,我必须将变量放在括号中,例如

$result = ["result" => ($row['ArtikelName']), "info" => "Ok"];

before encoding it. 在编码之前。 I hope this helps someone in the future. 我希望这可以帮助将来的某个人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM