2012-06-19 50 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);