通过ajax php发送数据

通过ajax php发送数据,php,javascript,ajax,jquery,Php,Javascript,Ajax,Jquery,尝试使用ajax将变量发送到php js: var test1 = "test" $.ajax({ type : "POST", url : "getid.php", data: {test1 : test1}, success: function() { console.log("message sent!"); } }); “消息已发送!”出现在控制台中 php: <?php $test1 = $_POST['test1

尝试使用ajax将变量发送到php

js:

var test1 = "test"
$.ajax({
    type : "POST",
    url : "getid.php",
    data:  {test1 : test1},
    success: function() {
         console.log("message sent!");
    }
}); 
“消息已发送!”出现在控制台中

php:

<?php 
$test1 = $_POST['test1'];
echo $test1; 
?> 
我真的不知道我做错了什么。。。有什么想法吗

执行操作时更新*

$.ajax({    
        type : "POST",
        url : "getid.php",
        data:  {"test1" : test1},
        success: function(msg) {
            console.log("message sent!");
            console.log(msg);
        }
}); 
此日志记录“测试”

在php中仍然会出现相同的错误..

更改jQuery代码:

var test1 = "test"
$.ajax({
    type : "post",
    url : "getid.php",
    data:  {"test1" : test1}, // this is the row that was causing the problem
    success: function(msg) {
         console.log(msg);
    }
}); 

您必须将
test1
放在引号中,因为它是一个包含“test”的定义变量,导致数据为
{“test”:“test”}

,因为响应作为参数提供给回调函数。试试这样的东西

var test1 = "test"
$.ajax({
    type : "POST",
    url : "getid.php",
    data:  {"test1" : test1},
    success: function(data) { // data argument here
         console.log("message sent!");
         console.log("data:",data); // log it out here 
    }
}); 

对象键不需要引用您是对的,但是
test1
是一个包含
test
的变量,它会更改键在这两种情况下,它仍然是“test1”:
a=“1”->"1"; b={a:2};->对象{a:2};b={“a”:2};->对象{a:2}
@Koiski我已经更新了success函数,将它复制粘贴到你的代码中,然后告诉我这个日志是什么,然后开始工作:)。“test”是您希望它显示的值。不,因为这样它会抛出一个查找常量的错误。这是
$\u POST['test1']
@AliBZ nope。请不要这样建议。对于您的更新:您需要添加
数据
作为成功函数的参数。我确实将其添加到了成功函数中function@Koiski添加
success:function(**data**){
它会记录“messagesent”“test”,但我在查看php时仍然会遇到相同的错误。$.get(“getid.php”),function(data){alert(“data Loaded:”+数据);});
var test1 = "test"
$.ajax({
    type : "POST",
    url : "getid.php",
    data:  {"test1" : test1},
    success: function(data) { // data argument here
         console.log("message sent!");
         console.log("data:",data); // log it out here 
    }
});