简体   繁体   English

PHP脚本向AJAX调用返回了意外的值

[英]PHP script returns an unexpected value to the AJAX call

My javascript: 我的JavaScript:

nombre = window.prompt('Escribe el nombre del autor/artista/letrista:','');
    if(nombre != ''){
      $.ajax({
          url: "admin/nuevo_autor.php",
          type: "POST",
          data: {autor: nombre},
          success: function (res) {
              alert(res);
              if(res=='verdadero'){
                  var opt = document.createElement('option');
                  opt.text = nombre;
                  opt.selected = true;
                  sel.add(opt);
              }
              return true;
          }
      });
    }

Calls 'nuevo_autor.php': 调用'nuevo_autor.php':

<?php
$nuevo = $_POST["autor"];
require("../includes/database.php");

$select = <<<EOT
SELECT * FROM autor
WHERE 1
EOT;
$resultado = $mysqli->query($select);
$res = "verdadero";
for($i=0;$i<$resultado->num_rows; $i++){
    $fila = mysqli_fetch_array($resultado, MYSQLI_ASSOC);
    if(stristr($fila["autor"], $nuevo)) {
        $res = "falso";
        break;
    }
}
echo json_encode($res);
?>

The Javascript alert shows: FIN (in spanish: END ). Javascript警报显示: FIN (西班牙语: END )。 Neither ' verdadero ' nor ' falso '. 既不是“ verdadero ”也不是“ falso ”。 I also tested using the $.get jQuery function with the same bad result. 我还使用$.get jQuery函数进行了测试,结果$.get相同。 Where is the error? 错误在哪里?

stristr($fila["autor"], $nuevo) will return "0" if $nuevo and $fila['author'] are equal, which in your code will be the equivalent of false . 如果$ nuevo和$ fila ['author']相等,则stristr($fila["autor"], $nuevo)将返回“ 0”,在您的代码中将等同于false

Instead you need to explicitly check for the false value, as in: 相反,您需要显式检查false值,如下所示:

if(stristr($fila["autor"], $nuevo) !== false) {
    $res = "falso";
    break;
}

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

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