PHP:问题在AJAX / JSON提交表单?表单、问题、PHP、JSON

2023-09-11 22:30:01 作者:资深情兽

目前我有以下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

提示:我使用的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.