dswe30290 2014-01-31 18:07
浏览 33
已采纳

点击按钮/链接执行PHP代码?

I have a shopping cart which uses PHP. When a person adds something to their cart, the relevant code is done at the top of cart.php, meaning they have to leave the product page as they add something to cart, and end up having to press the back button if they want to do more.

How do I execute PHP/SQL code when a user clicks "add to cart", but without redirecting them to a new page? I think Jquery/JSON is needed here, but I don't know the first thing about that. Something like the below:

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

Originally, I had:

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

The problem is that it takes them to a new page when I'm positive the logic can be done on the same page onclick of button.

  • 写回答

2条回答 默认 最新

  • duanquan1876 2014-01-31 18:11
    关注

    Do a POST request with jQuery,the page doesn't load since it is ajax..

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

    OR:

    Give a target to your form to an iframe which is hidden

    //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> 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度