2013-07-07 139 views
0

試圖發送一個帶有ajax的變量給php。發送數據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; 
?> 

錯誤消息:

Notice: Undefined index: test1... 

我真的不明白我做錯了這裏...任何想法?

做`

$.ajax({  
     type : "POST", 
     url : "getid.php", 
     data: {"test1" : test1}, 
     success: function(msg) { 
      console.log("message sent!"); 
      console.log(msg); 
     } 
}); 

這將記錄 「測試」

仍然獲得在PHP但同樣的錯誤時,UPDATE * ..

+1

不,因爲那麼它會拋出一個錯誤尋找一個常數。它是'$ _POST ['test1']'。 – Jimbo

+0

@AliBZ nope。請不要這樣建議。 – itachi

+0

爲了您的更新:您需要添加'data'作爲成功函數的參數。 – mishik

回答

2

影響你的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"}

+0

對象鍵不需要引號 – mishik

+1

您說對了但是'test1'是包含變量'test'從而改變密鑰 –

+0

在兩種情況下,它仍然是「test1」:'a =「1」; - >「1」; b = {a:2}; - > Object {a:2}; b = {「a」:2}; - >對象{A:2};' – mishik

0

及其becouse響應iable含有「測試」是考慮到回調函數作爲參數。嘗試像這樣的東西

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 
    } 
}); 
+0

它日誌「消息發送」「測試」,但我仍然在看php時得到相同的錯誤。 $ .get(「getid.php」,function(data){ \t \t alert(「Data Loaded:」+ data); \t}); – Koiski