繁体   English   中英

通过AJAX将数组发送到php

[英]Send array to php via AJAX

我尝试通过ajax将JS数组发送到php文件。

JS代码:

$('#basket').on('click',function(){

    $.ajax({
        type: "GET",
        url: "basket.php",
        data: {vektor: itemNameArray},
        success: function(){

            window.location.href ="basket.php";
            console.log(itemNameArray);

        }
    });

});

php代码:

<?php
    echo("<script>console.log('PHP: test 1');</script>");
    if(isset($_GET['vektor'])){
        echo("<script>console.log('PHP: test 2');</script>");
        $vektor = $_post['vektor'];
        echo("<script>console.log('PHP: ".$vektor."');</script>");
    }

但是似乎我无法获得关键的矢量。 我进入日志我的数组和测试1的第一个回声,但不是第二个。 我需要将数组发送到php文件以创建html代码。 那是因为我需要打开“ basket.php”才能看到结果。

嗨,您可以这样操作:

您的php脚本:

if (isset($_POST["action"])) {
   $action = $_POST["action"];
   switch ($action) {
    case 'SLC':
     if (isset($_POST["id"])) {
       $id = $_POST["id"];
       if (is_int($id)) {
       $query = "select * from alumni_users where userId = '$id' ";
        $update = mysqli_query($mysqli, $query);
         $response = array();
         while($row = mysqli_fetch_array($update)){
           .......fill your response here

         }
         echo json_encode($response);
        }
       }
      break;

    }
 }
Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter

then in your ajax:



function getdetails() {
 var value = $('#userId').val(); // value can be your array ! note: if you send a object json_encode(json_decode(,MyObj,true))
                         return $.ajax({
                              type: "POST",
                              url: "getInfo.php",
                              data: {action: "SLC",id: value } 
                          })
                      }
                      call it like this:



   getdetails().done(function(response){
                  var data=JSON.parse(response);
                  if (data != null) {
                  //do somthing with your Data
                  }
                  })

我已更改GET并将其发布到POST。 您搞砸了POST和GET,这是第一个主要错误。

但是似乎我无法获得关键的矢量。 我进入LOG我的数组和测试1的第一个回声,但没有第二个(不发布POST) 我需要将数组发送到php文件以创建html代码。(对于这种类型的数据,最好使用POST ),这是因为我需要打开“ basket.php”以查看结果。

$('#basket').on('click',function(){

            $.ajax({
                type: "POST",
                url: "basket.php",
                data: {vektor: itemNameArray},
                success: function(){

                    //window.location.href ="basket.php";
                    console.log(itemNameArray);

                }
            });

        });

php代码:

<?php
echo("<script>console.log('PHP: test 1');</script>");
  if(isset($_POST['vektor'])){
     echo("<script>console.log('PHP: test 2');</script>");
     $vektor = $_POST['vektor'];
     echo("<script>console.log('PHP: ".$vektor."');</script>");
 }

暂无
暂无

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

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