简体   繁体   English

Ajax - jQuery 和 Ajax 错误/不工作

[英]Ajax - jQuery and Ajax errors/not working

I am building a webpage that contains a div which holds some data retrieved from a MySql database through PHP.我正在构建一个网页,其中包含一个div ,其中包含通过 PHP 从 MySql 数据库中检索到的一些数据。 This div shows some products and on its left there is a simple nav bar with different categories.这个 div 显示了一些产品,在它的左边有一个带有不同类别的简单导航栏。 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.我试图做的是,当用户单击此导航栏的某个类别时, div的内容将发生变化,显示该类别的所有产品都存储在 db 中。 So I tried using Ajax (my first time btw), and I can't seem to make it work.所以我尝试使用 Ajax(顺便说一句,我的第一次),但我似乎无法让它工作。 My project structure is something like this:我的项目结构是这样的:

Parent directory父目录

  • php > index.php php > index.php
  • css > index.css css > index.css
  • js > index.js js > index.js
  • img > images here img > 图片在这里
  • ajax> products-ajax.js / products-ajax.php ajax> 产品-ajax.js / 产品-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. index.php 文件链接到 index.js 和 products-ajax.js 但是,我已经尝试在 index.js 和 index.php 中包含 Ajax 代码行,但我无法让它从products-ajax.php 任何帮助表示赞赏。

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)});

});

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() ).使用$.ajax()而不是$.post() ,您可以添加一个错误处理程序,它会给您提供宝贵的信息(也许您可以使用$.post() ,但我不熟悉这个函数,afaik 是只是$.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.编辑:并且更喜欢console.log()而不是alert()进行调试。 Especially with asynchronous interactions, alert() sometimes leads to surprises...特别是对于异步交互, alert()有时会导致意外......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM