2011-02-14 43 views
0

http://jsfiddle.net/boyee007/kS6Vr/獲取文本框的ID動態jQuery的PHP

我如何使用jQuery AJAX它傳遞給PHP

JQUERY AJAX檢索動態文本框ID:

$("#book_event").submit(function(e) { 
    $(this).find('input[id^=textbox]').each(function(i, e) { 
     $.post("Scripts/book_event.php", { att_name: $(e).val() }, function(data) { 
      if (data.success) { 
       $("#err").text(data.message).addClass("ok").fadeIn("slow"); 
      } else { 
       $("#err").text(data.message).addClass("error").fadeIn("slow"); 
      } 
     }, "json"); 
    }); 
    e.preventDefault(); 
}); 

以及如何獲得這些ID與PHP:

if(!$_POST['submit']) : 
    $att_name = trim($_POST['att_name']); 
endif; 

回答

2

我會收集所有的文本框輸入到JavaScript數組,然後將其發送到PHP腳本。這樣,你只需要一個ajax而不是n。

var input_array = {events:[]}; 
$("#book_event").submit(function(e) 
{ 

    $(this).find('input[id^=textbox]').each(function(i, e) 
    { 
     input_array.events.push(e.val()); 
    }); 


    //send array via ajax 
    $.ajax 
    ({ 
     url: "Scripts/book_event.php", 
     type:"POST", 
     data:JSON.stringify(input_array), 
     contentType: 'application/json; charset=utf-8', 
     dataType:"json", 
     success:function(data){//func on success}, 
     error:function(data){//func on error} 
    }); 

    e.preventDefault(); 
}); 
在服務器端

現在你必須以檢索已發送的JSON對象:

$dto = json_decode($GLOBALS["HTTP_RAW_POST_DATA"]); 

foreach($dto->events AS $event) 
{ 
    //do your work here 
} 
//output response 

我覺得應該有直接讀取HTTP_RAW_POST_DATA安全問題,這是更好的解碼前檢查到json