2012-06-19 41 views
0

我有以下提交給iframe的jquery函數。從PHP發回的消息是json。我無法弄清楚如何在jQuery中接收此消息,以便我可以將其顯示給用戶。jquery從PHP接收json消息

function IframeSubmit(){ 
    // remove iframe if exists 
    $('#hiddenIframe').remove(); 

    // change target attribute on form 
    form.attr('target', 'hiddenIframe'); 

    // create and add iframe to page 
    $('<iframe />', { 
     name: 'hiddenIframe', 
     id: 'hiddenIframe', 
     style: 'display:none' 
    }).appendTo('body'); 

    // on response from php file 
    $('#hiddenIframe').load(function(){ 
     // process received message here ... 
    }); 
} 

謝謝!

+1

使用ajax,echo a json obj通過php'json_encode($ string);' – gorelative

+1

'.load()'方法用於將html內容加載到元素中,而不是JSON。嘗試使用['.getJSON()'](http://api.jquery.com/jQuery.getJSON/),並在回調中處理結果。 – nnnnnn

+0

錯誤:getJSON()不是函數。 – user1002039

回答

0

我有一個類似的代碼:

$(document).ready(function(){ 
    $('form#myform').submit(function(){ 
      $("#hiddenIframe").remove();  
      $('<iframe name="hiddenIframe" />').appendTo('body').attr({'id': 'hiddenIframe'}); 
      var Frame = $('#hiddenIframe'); 
      var newSrc = 'about:blank?nocache=' + Math.random(); //force new URL 
      Frame.attr('src', newSrc); 
      var iframe = $('#hiddenIframe').load(function(){ 
       var response = iframe.contents().find('body').html(); 
       var txt = $.parseJSON(response); 
       $('#message').append(txt.message); 
       if(txt.error == false){ 
        $.ajax({ 
         type: 'POST', 
         url: '?myurl', 
         dataType: 'json', 
         data: { 
          //some data 
         }, 
         success: function(data){ 
          //some action 
         } 
        });           
       }   
     });            
    }); 
}); 

在iframe中的輸出爲:

var response = iframe.contents().find('body').html(); 
var txt = $.parseJSON(response); 

讀出響應,如:或txt.error txt.message

PHP部分:

$this->message['error'] = true; 
$this->message['message'] = "Problem!"; 

echo/print json_encode($this->message);