dtoqa66028 2012-11-19 07:04
浏览 84
已采纳

jQuery ajax返回undefined

I am trying to return a row from my database where the id sent via jquery to the php matches a field value. I am getting back undefined and can't seem to work my way out of it.

My jquery:

function renderPreview( event ) {
    target = event.target.id;

    console.log(target) // should say the id name

            $('#results').removeClass();
            $('#results').addClass(target).html( $('#textInput').val() );
            $('html, body').animate({ scrollTop: 600}, "slow");

    console.log('start ajax')

    $.ajax({
        url: '../test.php',
        type: 'POST',
        data: [{'class' : target}],
        dataType: 'json',
        success: function(data) {
            var id = data[0];
            var name = data[1];
            var style = data[2];
            $('#codeTest').html("<b>id: </b><br />"+id+"<br /><b> name: </b><br />"+name+"<br /><b> style: </b><br />"+style);
        }
    });
};

PHP:

$dbstylename = $_POST['class'];
$result = mysql_query("SELECT * FROM style where stylename like '$dbstylename'");
$array = mysql_fetch_row($result);

echo json_encode($array);

mysql_close($con);
?>

Also is there a line of code I can put in my jquery or php to see what query is going through in my chrome developer console?...like the console.logs I already have.

  • 写回答

1条回答 默认 最新

  • dshqd84261 2012-11-19 07:44
    关注

    The problem is that you are not sending the data in the correct way. jQuery is passing the value you assign to the data: property to jQuery.param. This function converts the data to a proper query string.

    But if you pass an array instead of an object, .param expects it to be an array of objects, where each of the objects has a name and value property.

    You can see what jQuery generates in your case by calling .param directly:

    > jQuery.param([{'class' : target}])
      "undefined=undefined"
    

    You get the correct query string, if you pass either

    [{name: 'class', value: target}]
    

    or

    {'class': target}
    

    Both generate:

    "class=<whatever the value of target is>"   
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料