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...

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

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R