简体   繁体   English

Ajax函数返回总是错误

[英]Ajax function return always error

I need to pass some value to a PHP file and from this return some values to the original script. 我需要将一些值传递给PHP文件,并从中将一些值返回给原始脚本。 I wrote this code. 我写了这段代码。

$(document).ready(function() {
    var value = $('#myId').val();
    $('.myClass').click(function() {
        var request = $.ajax({
            type:   'POST',
            url:    'getinfo.php',
            data:   {fileIs: value},
            success: function(data) {
                alert(data);
            },
            error: function() {
                alert("Error"); 
            }
        });

        });   
    });

getinfo.php is like: getinfo.php就像:

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());

if(isset($_REQUEST['fileIs'])) {
    $file = mysql_real_escape_string(htmlentities($_POST['fileIs']));
    $value = mysql_query("SELECT * FROM files WHERE filename = '".$file."' ");
    while($row = mysql_fetch_array($value)) {
        echo $row['fileTitle']; 
    }       
}

When i execute the script php AJAX function always return the alert with wrote "Error" that disappear automatically. 当我执行脚本php AJAX函数时,始终返回写有“错误”且自动消失的警报。 How can i fix this problem? 我该如何解决这个问题? My goal is to send "value" variable content to the PHP file and get response from it to have the content in database corresponding to "value" content. 我的目标是将“值”变量内容发送到PHP文件并从中获取响应,以使数据库中的内容与“值”内容相对应。

The ajax function can't tell what type of data is being returned because you aren't setting the header of the http response in the php code. Ajax函数无法确定返回的数据类型,因为您没有在php代码中设置http响应的标头。 Adding the following before the while loop should help: 在while循环之前添加以下内容将有所帮助:

header("Content-type: text/plain; charset=utf-8");

Documentation: http://php.net/manual/en/function.header.php 文档: http : //php.net/manual/en/function.header.php

Try json_encode in getinfo.php getinfo.php中尝试json_encode

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());

if(isset($_REQUEST['fileIs'])) {
$file = mysql_real_escape_string(htmlentities($_POST['fileIs']));
$value = mysql_query("SELECT * FROM files WHERE filename = '".$file."' ");
while($row = mysql_fetch_array($value)) {
         $result = $row['fileTitle']; 
                        }       
}
echo json_encode($result);  or  //use one
return $result;                 //optional

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

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