簡體   English   中英

ajax表單處理數組

[英]ajax form handling an array

我正在嘗試處理提交表單數據后來自php文件的數組,提交表單后數據的值是= ARRAY,但我不能以任何方式使用此數組,任何想法我該如何處理該數組!

Javascript:

   $('#file').live('change',function(){
       $('#preview').html('');
       $('#preview').html('<img src="loader.gif" />');
       $('#data').ajaxForm(function(data){
               $(data['toshow']).insertBefore('.pic_content').hide().fadeIn(1000);

       }).submit();

  });

PHP的:

....
....etc
echo json_encode(array('toshow'=>somedata,'data'=>somedata));

JSON字符串來自服務器

{"toshow":"\r\n\t\t\t\t\r\n\t\t<table class=\"out\">\r\n\t\t\t<tr ><td class=\"img\"><a title=\"2012-06-02 01-22-09\" rel=\"prettyPhoto\" href=\"img\/2012-06-02 01-22-09.284.jpg\"><img  src=\"img\/thumb\/2012-06-02 01-22-09.284.jpg\"\/><\/a><\/td><\/tr>\r\n\t\t\t\r\n\t\t\t<td>\r\n\t\t\t\t<table cellSpacing=\"1\" cellPadding=\"0\">\r\n\t\t\t\t\t<tr><td class=\"data\"><span class=\"click\">2012-06-02 01-22-09<\/span><\/td><\/tr>\r\n\t\t\t\t\t<tr><td class=\"data\"><span class=\"click\">Download<\/span><\/td><\/tr>\r\n\t\t\t\t\t<tr><td class=\"data\"><a href=\"img\/2012-06-02 01-22-09.284.jpg\"><span class=\"click\">View<\/span><\/a><\/td><\/tr>\r\n\t\t\t\t<\/table>\r\n\t\t\t<\/td>\r\n\t\t\t<\/tr>\r\n\t\t<\/table>","span":"<span class='text'><img src='greencheck.png'\/>2012-06-02 01-22-09 Uploaded ,File Size =152Kb <\/span>"}

最好使用json_encode($ array)將array轉換為json格式。 JSON數據可以很容易地用Javascript處理

您不能直接回顯數組,它只會輸出Array

您需要使用json_encode

echo json_encode($your_array);

您也可以使用jQuery通過PHP處理數組

供jQuery使用-每個jQuery

供PHP使用-foreach或for循環

或嘗試

echo '<pre>';
print_r($array);
echo '</pre>';

在PHP端,您必須在JS端插入json_encode($array) AND,而不是使用data['toshow'] data.toshow data['toshow'] use data.toshow

希望能幫助到你!

發送一個JSON響應,例如從PHP中發送:

<?php
echo json_encode($yourarray);
?>

然后調整您的AJAX功能,執行以下操作:

  $('#file').live('change',function(){
       $('#preview').html('');
       $('#preview').html('<img src="loader.gif" />');
       $('#data').ajaxForm(function(data){
               var jsonData = jQuery.parseJSON(data);
               //acess it like
               alert(jsonData.toshow); //alert for your testing
               $(jsonData.toshow).insertBefore('.pic_content').hide().fadeIn(1000);

       }).submit();

  });
  • 編輯*更改,根據插件文檔進行更新。

從未使用過.ajaxForm jQuery插件,我查閱了文檔,然后將代碼放在這里,從閱讀的內容中看得盡可能清楚,我什至讓插件將響應自動解析為JSON。

我沒有看到任何.ajaxForm()。submit(),並且根據文檔沒有必要。

$('#file').live('change',function(){
    $('#preview').html('');
    $('#preview').html('<img src="loader.gif" />');
        $('#data').ajaxForm({ 
            dataType:  'json',
            success:   function(data){
                alert("json string response from php: "+ data.toshow);
                $(data.toshow).insertBefore('.pic_content').hide().fadeIn(1000);    
            }
        }); 
});

dataType使插件單獨解析對json的響應。 成功:僅當PHP響應時,函數(數據)才會發生。 請仔細實施,如果仍然無法正確操作,請提供鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM