【问题标题】:show a record in PHP from mysql via $.AJAX and JSON通过 $.AJAX 和 JSON 从 mysql 显示 PHP 记录
【发布时间】:2015-07-30 11:43:02
【问题描述】:

我正在 PHP(buscador.php) 中的搜索页面上工作,我需要根据输入的 ID 显示(始终在同一页面 buscador.php 中)员工信息,为此我编写了一个Jquery 函数使用 $.ajax 以通过 AJAX 和 JSON 格式获取数据(数据库查询编码在 process.php 中)

我的问题是,当我定义 ID 并单击提交按钮时,它会将我重定向到 process.php,而不是在 buscador.php 内的特殊区域中显示信息,信息 process.php 显示为:

{"users":{"status":"OK","0":{"ID":"001","Nombre":"algo","cargo":"algo cargo"},"1":{"ID":"PHP001","Nombre":"Pablo Ernesto Tobar Mayora","cargo":"Web Programmer"},"2":{"ID":"PHP002","Nombre":"Pabletoreto Blogger","cargo":"Blogger Manager"},"3":{"ID":"PHP003","Nombre":"prueba de stored procedure en MySQL","cargo":"Database Administrator"},"4":{"ID":"PHP004","Nombre":"Prueba de funciones en MySQL","cargo":"Database Tester"}}}

这不是我要寻找的结果,但正如您所见,对数据库的查询已完成,除此之外,信息以 JSON 格式显示,但我无法在 buscador.php 页面中显示该信息,请你告诉我我做错了什么,我的整个代码是:

buscador.php

<html lang="es-ES">
<head>
<meta name="tipo_contenido"  content="text/html;" http-equiv="content-type" charset="utf-8">
<link type="text/css" rel="stylesheet" href="content/estilos.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="javascript/jquery.js" type="text/javascript"></script>

<title>BUSCADOR</title>
</head>
<form method="post" id="form_id" action="process.php">
<fieldset>
<legend> Buscador Asincrono</legend>
 <p>ID a buscar: <input type="text" name="ID_name" id="ID_id"/><div id="estado_id"></div></p>
 <p><input type="submit" id="submit_id" value="Buscar"/></p>
 <img src="imagenes/cargando.gif" id="LoadingImage"  style="display:none" align="center"/>
 <div id="ajax_id"><b>Person info will be listed here...</b></div>
 <div id="msg">
<table id="infoemp" border="1" style="display:none" align="center">
<thead>
<th>ID</th>
<th>Nombre</th>
<th>Cargo</th>
</thead>
<tbody></tbody>
</table>
</div>
</fieldset>
</form>
</html>

jquery.js

$(document).ready(function() {
  $("#form_id").submit(function(e){
    e.preventDefault(); 
     if(validaForm()){  
       requestInfo();
    } 
  });
});

function validaForm(){
        var id_val = $("input#ID_id").val().trim(); 
        //var id_val = id.val().trim();
        if((id_val=="") || id_val.replace(/s+/,'') == ''){
            alert("Favor ingrese el ID");
            $("input#ID_id").addClass("posicionamiento");
            $("#ajax_id").html("<div class='error'>Debe especificar el nombre</div>");
            return false;
        }else{  
        $("input#ID_id").removeClass("posicionamiento");
        $("#div_id").empty();
        }
        return true;
}   

   function requestInfo(){

    $("#submit_id").hide();
    $("#ajax_id").html("");
    $("#LoadingImage").show();
    $("#ajax_id").html("<div class='cargando'> realizando busqueda</div>");

    var url = $("#form_id").attr('action'); 
    var data = $("#form_id").serialize();   
    var type = $("#form_id").attr('method');
    alert(url);

    $.ajax({
    url:url,          
    data:data,       
    type:type,      
    cache: false,  
    contentType: "application/x-www-form-urlencoded", 
    dataType: 'json', 
    encode: true,
       }); 

.done(function(data) { 
if(data.status == "OK"){
$("#submit_id").show();
$("#ajax_id").html("");
$("#LoadingImage").fadeOut();   
$("#infoemp").show();

$.each(data.users, function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.ID+"</td>"
+"<td>"+user.Name+"</td>"
+"<td>"+user.cargo+"</td>"
+"</tr>" ;
$(tblRow).appendTo("#infoemp tbody");
});
} else {  $("#ajax_id").html(data.status).addClass("cargando"); }
});

.fail(function( jqXHR, textStatus, errorThrown ) {
  if ( console && console.log ) {
       console.log( "La solicitud a fallado: " +  textStatus);
     }
    });

    }

进程.php

<?php

$bd = "ejemplo";
$server ="localhost";
$user = "root";
$password = "";

if (isset($_POST['Submit']) && isset($_POST['ID_name'])) {
    $valor = filter_var($_POST['ID_name'], FILTER_SANITIZE_STRING);

    $var = array();

    if ($valor == null)
    $var["status"]="ERROR";
    exit(); 
    } else {

    $mysqli = mysqli_connect($server, $user, $password, $bd);
    if( ! $mysqli ) die( "Error de conexion ".mysqli_connect_error() );

$var["status"]="OK";
$sql = "SELECT * FROM empleado_php";

$result = mysqli_query($mysqli, $sql);

while($obj = mysqli_fetch_assoc($result)) {

$var[] = $obj;
}

$mysqli->close(); 
   }
echo '{"users":'.json_encode($var).'}';
header('Content-type: application/json; charset=utf-8');

?>

【问题讨论】:

  • 你为什么要这么做echo '{"users":'.json_encode($var).'}
  • 您已经在阻止默认操作。有没有错误?
  • 您好,是的,我已经阻止了默认操作,我不明白为什么它会重定向到 process.php
  • 我使用 {"users":'.json_encode($var).'} 来用 $.each 迭代结果
  • @PabloTobar 1) 您是否在控制台中收到任何 JS 错误? 2) alert(url) 是否发生过?

标签: php jquery mysql ajax json


【解决方案1】:

你有 JS 错误。

删除此 sn-p 中 }) 之后的分号:

    encode: true,
       }); 

.done(function(data) { 
if(data.status == "OK"){

对这个sn-p做同样的事情,去掉}之后的分号)

} else {  $("#ajax_id").html(data.status).addClass("cargando"); }
});

.fail(function( jqXHR, textStatus, errorThrown ) {
 

这将解决此特定问题,如果您在循环时遇到 PHP 错误或更多 JS 错误,请先谷歌您的问题,如果找不到,请在此处发布。另外,尝试this question 学习如何查找 JS 错误。注意:我刚刚看到您在发布答案之前弄清楚了如何查找 JS 错误。干得好:)

【讨论】:

  • 感谢@rick6 我已经删除了 )};但没有解决问题,我已经用谷歌搜索了,但没有找到答案,但会继续搜索
  • @PabloTobar 两者兼得。这就是问题所在。
  • @PabloTobar 并且只删除分号,而不是整个括号和括号。你走得太快了。慢下来,看看我的回答:)
  • 是的,在 .done 之前和 .fail 之前得到 --> SyntaxError: invalid property id .done(function(data) { line 47 jquey.js in firebug
  • 它有效,非常感谢您的耐心等待,我只有一个问题,我无法使用以下方法获取值 data.status:$("#ajax_id").html(data.status );在进程 .php 我定义了 $var["status"]="ERROR" 或 $var["status"]="OK";但在 buscador.php 中它只显示:未定义,你能通过这种方式帮助我还是我应该打开另一个帖子...无论如何感谢你的耐心
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 2015-03-01
  • 2020-04-26
  • 1970-01-01
相关资源
最近更新 更多