dongmei2956 2015-07-09 13:55
浏览 16

使用js ajax从html发布到php帖子

im new to js and ajax and need a little bit of help. im trying to make cart quantity with js, after the user pressing the add_cart button I want to get the quantity of items the user wants and post it via php post, after pressing the button im getting 0 results from the post.

so here it goes:

$id = bin2hex(openssl_random_pseudo_bytes(8));
$value = 1;
$list .= "<div id='single_product'>
          <a href='details.php?pro_id=$pro_id'><img src='admin_area/product_images/$pro_image' width='100%' height='60%' /></a>
          </br>
          <h3>$pro_title</h3>
          <p style='color:gray; text-decoration: line-through;'> $pro_fullprice ₪ :מחיר</p>
          <p style='color:#ff66ff; font-weight: bold; '> $pro_price ₪ :מחיר שלנו</p>
          </br>
          <a href='index.php?add_cart=$pro_id'><button class='button_addCart' value='submit' onclick='javascript:post();' >הוסף לסל</button></a>
          <form name='f1' method='post' action='../index.php'>
            <input type='button' name='inc' onclick='javascript:document.getElementById(\"$id\").value++;' value='+' />
            <input type='number' name='quan' style='width:25%;' id='$id' value='$value' min='1' />
            <input type='button' name='dec' onclick='javascript:document.getElementById(\"$id\").value--;' value='-' /> 

            <script type ='text/javascript' src='js/jquery.min.js'></script>
            <script type='text/javascript'>
                function post()
                {
                    var value=document.getElementById(\"$id\").value;

                    $.post('functions.php',{postname:value},
                    function(data)
                    {
                        $('#value').innerhtml(data);
                    });
                }
            </script>    
          </form>
         </div>" ;
  • 写回答

1条回答 默认 最新

  • douzao1119 2015-07-09 15:40
    关注

    There are multiple issues here. One issue is that all this code (according to you) is inside a while loop; this means that for every iteration you are creating the same JavaScript which does the same function, thus loading the DOM with unnecessary script. Another problem is the HTML, it is badly parsed, one example, you have a button that has its own function inside anchor links that have their own href. However, the biggest issue here is how it is all mangled up (its what they call "spaghetti code"). You need to separate things up in order to fix this. Try the MVC approach where you have the view that takes care of the parsing, and your functions file should act as the controller/model. I would do the following:

    Your functions.php should be a class with different functions. One of those should be a function that retrieves the data from your database get_products(), turns it into an array, and stores it in a variable. This variable is then returned. For demonstration purposes I will just hard code an array:

    //located in: app/functions.php
    
    class Functions {
        function get_products() {
            $products_array = array(
                array(
                    "id" => 1,
                    "image" => "test.jpg",
                    "fullprice" => 50,
                    "price" => 40,
                    "title" => "Some Name",
                    "quantity" => 2,
                ),
                array(
                    "id" => 2,
                    "image" => "test2jpg",
                    "fullprice" => 50,
                    "price" => 40,
                    "title" => "Some Name2",
                    "quantity" => 1,
                )
            );
            return $products_array;
        }
    
        function update_cart(){
            return "cart updated";
        }
    }
    
    //the code below will be needed to execute AJAX
    if (isset($_GET) && !empty($_GET)) {
        $res = $funcs->$_GET['function']();
        return json_encode($res);
    }
    

    Your "view" should have anything you want to parse in the DOM. In this case, we are calling the function get_products() from your functions.php file, then parsing the array thourgh the page. Notice we are also linking the JavaScript file needed:

    <!-- located in: app/product.php -->
    
    <?php
    include("functions.php");
    $funcs = new Functions();
    $products = $funcs->get_products();
    ?>
    
    <script src='js/jquery.min.js'></script>
    <script src='products.js'></script>
    <?php foreach ($products as $prod) { ?>
        <div class='product'>
    
            <a href='details.php?pro_id=<?= $prod["id"] ?>'>
                <img src='admin_area/product_images/<?= $prod["image"] ?>' width='100%' height='60%'/>
            </a>
    
            <h3><?= $prod["title"] ?>></h3>
    
            <p style='color:gray; text-decoration: line-through;'> <?= $prod["fullprice"] ?> ₪ :מחיר</p>
    
            <p style='color:#ff66ff; font-weight: bold; '> <?= $prod["price"] ?> ₪ :מחיר שלנו</p>
    
    
            <input class="plus" type='button' value='+'/>
            <input class="quantity" type='number' value='<?= $prod["quantity"] ?>' min='1'/>
            <input class="minus" type='button' value='-'/>
    
            <input class="product_id" type="hidden" value="<?= $prod["id"] ?>"/>
    
            <button class='button_addCart' value='submit'>הוסף לסל</button>
    
        </div>
    <?php } ?>
    <div id="results"></div>
    

    Your script takes care of the functionality using jQuery:

    //located in app/products.js
    
    $(document).ready(function () {
        $(".plus").click(function () {
            var $product_elem = $(this).closest(".product");
            var $quantity_elem = $product_elem.find(".quantity");
            $quantity_elem.val(parseInt($quantity_elem.val()) + 1);
        });
    
        $(".minus").click(function () {
            var $product_elem = $(this).closest(".product");
            var $quantity_elem = $product_elem.find(".quantity");
            $quantity_elem.val(parseInt($quantity_elem.val()) - 1);
        });
    
        $(".button_addCart").click(function () {
            var $product_elem = $(this).closest(".product");
            var quantity = $product_elem.find(".quantity").val();
            var id = $product_elem.find(".product_id").val();
            var postdata = {
                product_id: id,
                quantity: quantity
            };
            var url = "functions.php?function=update_cart";
            $.post(url, postdata, function (data) {
                console.log(data);
                $('#results').html(data);
            });
        });
    });
    

    I hope this helps.

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP