doswy02440 2015-10-27 19:59
浏览 63
已采纳

Ajax - jQuery和Ajax错误/无效

I am building a webpage that contains a div which holds some data retrieved from a MySql database through PHP. This div shows some products and on its left there is a simple nav bar with different categories. What I am attempting to do is that when the user clicks a category of this nav bar, the content of the div will change, showing the products of that category all of which are stored in the db. So I tried using Ajax (my first time btw), and I can't seem to make it work. My project structure is something like this:

Parent directory

  • php > index.php
  • css > index.css
  • js > index.js
  • img > images here
  • ajax> products-ajax.js / products-ajax.php

The index.php file is linked to both index.js AND products-ajax.js However, I have already tried including the Ajax line of code in both index.js and index.php but I can't make it recieve data back from products-ajax.php Any help is appreciated.

And here's what my test code looks like:

/* THIS IS THE products-ajax.js */

$(document).ready(function(){
    $('.products-list li').click(function(){

        $.post("products-ajax.php",
               {p: "Product name"},
               success: function(data){alert(data)}
        );
        
    });
});
<?php

/* THIS IS THE products-ajax.php */

$p = $_POST['p'];

echo $p;

?>

I realized my broswer's debugger says there's a missing parentheses:

$('.products-list li').click(function(){
 //The debugger says HERE v should go a parentheses
$.post("products-ajax.php", {p: "Product name"}, success: function(data{alert(data)});

});
</div>
  • 写回答

1条回答 默认 最新

  • dousong1992 2015-10-27 20:21
    关注

    Using $.ajax() instead of $.post(), you could add an error handler which would give you precious information (maybe you can with $.post(), but I'm not familiar with this function, which afaik is just a shortcut to $.ajax()). It could be something like :

    var request = $.ajax({
        url: "products-ajax.php",
        method: "POST",
        data: { p: "Product name" }
    });
    request.done(function( data ) {
        alert( data );
    });
    request.fail(function( jqXHR, textStatus ) {
        alert( "Request failed: " + textStatus );
    });
    

    Edit: and prefer console.log() rather than alert() for debugging. Especially with asynchronous interactions, alert() sometimes leads to surprises...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵