JQuery Ajax出错了

时间:2017-11-27 17:46:12

标签: javascript php jquery ajax

将dataType设置为Json后,我的ajax函数出错了。 那是代码:

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);
}
?>

出了什么问题? 谢谢

2 个答案:

答案 0 :(得分:0)

你可以试试这个

$(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);
    }

答案 1 :(得分:0)

您可以通过将功能更改为此来找出错误:

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

这会告诉你它失败的原因,可能是通用的,但比'错误'

更好

另请注意:

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