繁体   English   中英

尝试使用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(text.php):

<?php 

$src1= $_POST['source1'];  
$src2= $_POST['source2'];     

echo $src1; 
echo $src2;

?>

问题:什么都没发生......没有错误......没什么。 我没有看到'echo1'和'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
     });
});

参考ajax

暂无
暂无

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

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