1

这是我的ajax调用

<script src = "js/jquery.js" type = "text/javascript"></script>
<script type="text/javascript">

$(document).ready(function(){

    $('#DepartmentNameDropdown').change(function(){

        $('#DepartmentName').attr('value', document.getElementById("DepartmentNameDropdown").options[document.getElementById("DepartmentNameDropdown").selectedIndex].text);                                 

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "http://localhost:8081/crownregency/getInfo.php",
        data: {id : $('#DepartmentNameDropdown').val()}, //data: {status: status, name: name},
        success:function(data){
            $('#DepartmentDescription').attr('value', data.Desc);
        }           
    });
});                    
});
$('#DepartmentName').attr('value', $('#DepartmentNameDropdown').text());    

</script>

这是我的 getinfo.php

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("jkings");
$value = $_POST['id'];
$query = mysql_query("SELECT * FROM department WHERE dept_ID = $value");
$row = mysql_fetch_array($query);
$desc = $row['dept_desc'];
$mission = $row['dept_mission'];
$struct = array('Desc' => '$desc', 'Mission' => '$mission');
session_start();
$_SESSION['id'] = $value;

echo json_encode($struct);
//echo $row['dept_desc'];
?>

我不知道我在代码中哪里犯了错误,但似乎我无法访问 json 响应。我已经尝试了不同的方法,我还在学习这个 ajax 和 json,所以我很难看出我在哪里犯了错误

4

2 回答 2

0

我不完全确定,但我认为你可能需要改变

$('#DepartmentDescription').attr('value', data.Desc);

进入

$('#DepartmentDescription').attr('value', data['Desc']);

还,

$struct = array('Desc' => '$desc', 'Mission' => '$mission');

应该改为

$struct = array('Desc' => $desc, 'Mission' => $mission);

于 2012-08-17T02:06:12.800 回答
0

你的javascript似乎很好我会建议这个来检测问题可能出在哪里

 $.ajax({
    type: "POST",
    dataType: "json",
    url: "http://localhost:8081/crownregency/getInfo.php",
    data: {id : $('#DepartmentNameDropdown').val()}, //data: {status: status, name: name},
    success:function(data){
         alert(data.Desc)// should alert [object object] if all is well with your php code
        $('#DepartmentDescription').attr('value', data.Desc);
    }           
});

我真的很怀疑,但可能是区分大小写的问题,所以可能会改变

dataType:'json' to dataType:'JSON'

另外,如果您使用的是 chrome,请使用开发人员工具查看是否存在 javascript 错误(为 safari 开发)

于 2012-08-17T02:16:34.603 回答