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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19462649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:31:53  来源:igfitidea点击:

Trying to pass variable values from JavaScript to PHP using AJAX

javascriptphpjqueryajax

提问by Gandalf

I want to pass some values from JavaScript to PHP using jQuery/AJAX. I have the following "simplified" code, not sure what is that I am doing wrong. There seems to be quite a few similar questions/answers in StackOverflow, but none of the them are really helping.

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

HTML:

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 (text.php):

<?php 

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

echo $src1; 
echo $src2;

?>

The problem: Nothing is happening...no errors..nothing. I don't see the values of 'source1' and 'source2' showing up in the PHP echo statements.

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

采纳答案by hjpotter92

You need to include a success handlerin your AJAX call:

您需要在 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 );
        }
    });
});

and in your console, you'll receive:

在您的控制台中,您将收到:

some textsome text 2

Do make sure that both the test.phpand your html source files are in same directory.

请确保test.phphtml 源文件和 html 源文件都在同一目录中。

回答by Rituraj ratan

$("#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
     });
});

reference ajax

参考ajax