-4

jsファイルからphpファイルに変数を渡す方法。checker.jsからtest.phpに変数が必要です。

function SendData(id){
    $.ajax({
        type: "POST",
        url: "test.php",
        data: "id=" + id,
        cashe: false,
        success: function(response){
            alert("Record successfully updated")
        }
    })
}
$(document).ready(function(){
    SendData(10)
})

test.phpファイル

<?php
var_dump($_POST);
?>

index.html

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="checker.js"></script>
</head>
<body>
</body>
</html>
4

2 に答える 2

0

関数に構文エラー(または不明なキー)がありSendDataます。に変更cashecacheます。

そして、PHPにコードが書かれているものを見ることができません。alert(response);

index.htmlのコンテンツをtest.phpの応答に置き換える場合は、次を使用します。

function SendData(id){
    $.ajax({
        type: "POST",
        url: "test.php",
        data: "id=" + id,
        cache: false,
        success: function(response){
            $("body").html(response);
        }
    })
}
$(document).ready(function(){
    SendData(10)
})
于 2012-10-29T13:55:23.983 に答える
0

これを試して、コンソールに何が記録されているかを確認してください。

function SendData(id){
    $.ajax({
        type: "POST",
        url: "test.php",
        data: "id=" + id,
        cache: false,
        success: function(response){
            console.log(response);
        }
    });
}
$(document).ready(function(){
    SendData(10)
});

サーバーから何かが返されていることはほぼ確実です。あなたはそれを探しているだけではありません。

IDを取得する場合は、phpを次のように変更できます。

<?php
var_dump(json_encode($_POST));
?>

そしてあなたのjsは:

function SendData(id){
    $.ajax({
        type: "POST",
        url: "test.php",
        data: "id=" + id,
        cache: false,
        success: function(response){
            var id = JSON.parse(response).id;
            //do something with id
        }
    });
}
$(document).ready(function(){
    SendData(10)
});
于 2012-10-29T14:09:50.433 に答える