JQuery Ajax goes in error



我的ajax函数将数据类型设置为JSON后会出错。那是代码:

ajax脚本:

$('#da').on("change",function() {
            $.ajax({
                url: "callAjaxIndex.php",
                type: "POST",
                dataType: "json",
                data: {
                    method: 1,
                    id: $('#da').val(),
                },
                success: function() {
                    alert('test');
                },
                error: function() {
                    alert('error');
                }
            });
        });

callajaxindex.php

<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
    $sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
    $query = $conn->query($sql);
    while ( $tariffe = $query->fetch_array() ) {
        $result[] = array(
            'id' => $tariffe['id_arrivo'],
            'nome' => $tariffe['nome_arrivo']
        );
    }
    echo json_encode($result);
}
?>

怎么了?谢谢

您可以尝试此

$(document).on('change', '#da', function(){
     $.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
        //data is that returned from callAjaxIndex.php file
     });
});

<?php
    require('includes/core.php');
    if ( isset($_POST['method']) ) {
        $sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
        $query = $conn->query($sql);
        while ( $tariffe = $query->fetch_array() ) {
            $result[] = array(
                'id' => $tariffe['id_arrivo'],
                'nome' => $tariffe['nome_arrivo']
            );
        }
        echo json_encode($result);
    }

您可以通过更改函数来发现错误:

//other code
error: function(data)
{
    console.log(data.responseText) 
}
//other code

这将告诉您为什么失败,可能是通用的东西,但比"错误"

更好

还注意:

  1. 这是通过电话完成的,因此请原谅任何错误
  2. 我宁愿将其视为评论,直到我可以使用机器来帮助更多:)

相关内容

最新更新