尝试使用 AJAX 将变量值从 JavaScript 传递到 PHP


Trying to pass variable values from JavaScript to PHP using AJAX

我想使用 jQuery/AJAX 将一些值从 JavaScript 传递给 PHP。我有以下"简化"代码,不确定我做错了什么。在StackOverflow中似乎有很多类似的问题/答案,但没有一个真正有帮助。

.HTML:

<div>
<a href="#" id="text-id">Send text</a>
<textarea id="source1" name="source1" rows="5" cols="20"></textarea>
<textarea id="source2" name="source2" rows="5" cols="20"></textarea>
</div>

JAVASCRIPT:

$("#text-id").click(function() {
$.ajax({
type: 'post',
url: 'text.php',
data: {source1: "some text", source2: "some text 2"}
});
});

PHP(文本.php):

<?php 
$src1= $_POST['source1'];  
$src2= $_POST['source2'];     
echo $src1; 
echo $src2;
?>

问题:什么都没有发生...没有错误..无。我没有看到 "source1" 和 'source2' 的值出现在 PHP echo 语句中。

您需要在 AJAX 调用中包含成功处理程序:

$("#text-id").on( 'click', function () {
    $.ajax({
        type: 'post',
        url: 'text.php',
        data: {
            source1: "some text",
            source2: "some text 2"
        },
        success: function( data ) {
            console.log( data );
        }
    });
});

在主机中,您将收到:

some textsome text 2

请确保 test.php 和 html 源文件位于同一目录中。

$("#text-id").click(function(e) {// because #text-id is an anchor tag so stop its default behaivour
e.preventDefault();
$.ajax({
type: "POST",// see also here
url: 'text.php',// and this path will be proper
data: {
       source1: "some text",
       source2: "some text 2"}
}).done(function( msg )
      {
       alert( "Data Saved: " + msg );// see alert is come or not
     });
});

参考阿贾克斯