如何使用jQuery将多个变量传递给PHP

How to pass multiple variables to PHP with jQuery

本文关键字:PHP 变量 何使用 jQuery      更新时间:2023-10-06

好的,伙计们希望你们也能帮我做这件事。我对jQuery和AJAX并不是很了解,可能我错过了一些非常简单的东西。我不能传递超过1个变量。我尝试过几种不同的方法,其中最接近我工作的是这个,但即使这样也没有奏效。

jQuery

$("#bodymes ul li span[contenteditable=true]").blur(function(){
            var weight_id = $(this).attr("id") ;
            var weightbody_mes = $(this).text() ;
            $.post( "../includes/bodymes_weight.php", { weightbodymes: weightbody_mes })  
                .done(function( data ) {   
                    $(".weightsuccess").slideDown(200); 
                    $(".weightsuccess").html("Weight Updated successfully"); 
                    if ($('.weightsuccess').length > 0) {
                        window.setTimeout(function(){
                            $('.weightsuccess').slideUp(200);
                        }, 4000);
                    }  
                    // alert( "Data Loaded: " + data);
            });
        });

所以基本上,如果我运行这个程序,它会非常好地工作,我的PHP脚本会处理它。请注意,当我启用并显示加载的数据时,它会显示正确的信息(来自weightbodymes的信息),我可以更新数据库。但是,一旦我添加了另一个变量{ weightbodymes: weightbody_mes, weightid: weight_id },它就不会显示警报框中加载的数据(如果我试图显示两个变量的信息,它正在工作,但它只向PHP提交一个变量,即:

    $weightid = $_POST['weightid'];
    $weight = $_POST['weightbodymes'];
    if ($insert_stmt = $mysqli->prepare("UPDATE body SET body_weight=? WHERE body_id='$weightid'")) {
            $insert_stmt->bind_param('s', $weight);
            // Execute the prepared query.
            if (! $insert_stmt->execute()) {
                header('Location: ../index.php?error=Registration failure: INSERT nwprogram1');
            }
    }

希望你能告诉我在哪里犯了错误以及如何改正。提前感谢!

使用JS/JQUERY发布AJAX请求下面是我在所有AJAX调用中使用的语法。

var first = 'something';
var second = 'second';
var third = $("#some_input_on_your_page").val();

///////// AJAX //////// AJAX //////////
    $.ajax({
        type: 'POST',
        url:  'page_that_receives_post_variables.php',
        data: {first:first, second:second, third:third},
        success: function( response ){
            alert('yay ajax is done.');
            $('#edit_box').html(response);//this is where you populate your response
        }//close succss params
    });//close ajax
///////// AJAX //////// AJAX //////////

PHP页面的代码page_that_receives_post_variables.PHP

<?php
$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
echo 'now do something with the posted items.';
echo $first; //etc...
?>