【问题标题】:Execute PHP code onclick of button/link?点击按钮/链接执行PHP代码?
【发布时间】:2014-02-24 13:25:42
【问题描述】:

我有一个使用 PHP 的购物车。当一个人向他们的购物车添加东西时,相关代码在 cart.php 的顶部完成,这意味着他们在向购物车添加东西时必须离开产品页面,并且如果他们想最终必须按下返回按钮做更多。

当用户单击“添加到购物车”时如何执行 PHP/SQL 代码,但不将他们重定向到新页面?我认为这里需要 Jquery/JSON,但我不知道第一件事。类似于以下内容:

//product page
<input type="button" value="3"/>
//when the button is clicked, do some SQL/PHP based on the value on the same page

原来,我有:

//product page
<form action="./cart.php" method="post">
    //some code for user to select whats to be submitted
    <input type="submit"/>
</form>
...
//cart page
//some logic relevant to taking value from product page and adding to cart
//then display cart contents

问题是,当我确定逻辑可以在同一个页面上单击按钮时完成时,它会将它们带到一个新页面。

【问题讨论】:

  • 我可以温和地建议您先进行更彻底的背景教育吗?在项目中学习肯定会很有趣,但它也很容易在你的知识上留下空白,这些空白可能会在未来给你带来困难。如果您正在构建购物车,那么您目前可能不知道很多事情。

标签: php jquery sql json pdo


【解决方案1】:

使用 jQuery 发出 POST 请求,页面不会加载,因为它是 ajax..

$('input[type="submit"]').on('click',function(){
    var data = $('your_input_element').val();
    $.post('./cart.php',{"data" :data},function(response) 
    {
        console.log(response);
    });
});

或者:

给你的form 一个target 给一个隐藏的iframe

//product page
<form action="./cart.php" method="post" target="iframe_target">
    //some code for user to select whats to be submitted
    <input type="submit"/>
</form>
<iframe id="iframe_target" name="iframe_target" src="#" style="display:none;"></iframe> 

【讨论】:

【解决方案2】:

您需要在 javascript 中使用 ajax 样式的处理程序。

使用 jquery,您可以处理点击并将购物车数据发送到 php 脚本:

$('button').click(function(e){
  $.post('url', {product_id:$(this).val(), function(){ // success });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    相关资源
    最近更新 更多