jQuery从PHP接收JSON消息 [英] Jquery receive json message from PHP

查看:74
本文介绍了jQuery从PHP接收JSON消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下提交给iframe的jquery函数.从PHP发送回的消息是json.我不知道如何在jquery中接收此消息,以便将其显示给用户.

I have the following jquery function that submits to an iframe. The message sent back from PHP is json. I can't figure out how can I receive this message in jquery so I can display it to the user.

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 ...
    });
}

谢谢!

推荐答案

我有一个类似的代码:

$(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中的输出是:

the output in iframe is:

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

读取响应,例如:txt.error或txt.message

read response like: txt.error or txt.message

PHP部分:

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

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

这篇关于jQuery从PHP接收JSON消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆