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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog