PHP:问题在AJAX / JSON提交表单? [英] PHP: Problem submitting form in AJAX/JSON?

查看:139
本文介绍了PHP:问题在AJAX / JSON提交表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有以下code:

currently I have following code:

home.php

<form name='myformname' id='myformid'>
    <input type='text' name='mytext1' value='abc'>
    <input type='text' name='mytext2' value='123'>
    <input type='submit' value='Submit'> 
</form>

<div id='textone'></div><div id='texttwo'></div>

_home.php

$arr = array( 'textone' => $_POST['mytext1'], 'texttwo' => $_POST['mytext2'] );
echo json_encode( $arr );

ajax.js

jQuery('#myformid').live('submit',function(event) {
    $.ajax({
        url: '_home.php',
        type: 'POST',
        data: $('#myformid').serialize(),
        success: function( data ) {
            // TODO: write code here to get json data and load DIVs instead of alert
            alert(data);
        }
    });
    return false;
});

在提交输出:

{"textone":"abc","texttwo":"123"}

问题

我要加载的 mytext1 textone DIV和 mytext2 texttwo DIV使用JSON数据_home.php

Question

I want to load mytext1 value in textone DIV and mytext2 value in texttwo DIV using json data in _home.php

提示:我使用的<一个href="http://stackoverflow.com/questions/3326614/how-to-load-more-than-one-divs-using-ajax-json-combination-in-zend/3326660#3326660">this回答上做链接点击事件相同的任务。但如何做到这一点的表单提交?

Hint: I am using this answer to do the same task on link click event. But how to do this on form submission ?

感谢

推荐答案

您只是想解析JSON和设置的div的值包含对吧?

You just wanna parse that JSON and set the divs to the values it contains right?

var divs = JSON.parse(data);
for (var div in divs) {
  document.getElementById(div).innerHTML = divs[div];
}

(previous海报的语法可能更喜欢你追求的是什么,也许是更多的跨浏览器兼容,但不包括在JSON解析。)

(Previous poster's syntax is probably more like what you're after, and maybe is more cross-browser compatible, but doesn't include the JSON parsing.)

由于JSON是JavaScript的一个子集,你可以的eval()它。 JSON.parse()基本上没有了,但给你保证,如果数据包含一些讨厌的code,而不是一个简单的对象,它不会被评估。

Since JSON is just a subset of JavaScript, you can just eval() it. JSON.parse() basically does that, but gives you assurances that if 'data' contains some nasty code instead of a simple object, it won't be evaluated.

这篇关于PHP:问题在AJAX / JSON提交表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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