PHP: Problema presentando el formulario en AJAX / JSON?
Pregunta
Actualmente He siguiente código:
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;
});
Salida en enviar:
{"textone":"abc","texttwo":"123"}
Pregunta ??h1>
Quiero carga MyText1 valor en TextOne DIV y mytext2 valor en texttwo DIV utilizando datos JSON en _home.php
Sugerencia: Estoy utilizando esta respuesta hacer la misma tarea en el evento de clic de enlace. Pero, ¿cómo hacer esto en el envío de formularios?
Gracias
Solución
Sólo quiero analizar JSON y que establece los divs a los valores que contiene la derecha?
var divs = JSON.parse(data);
for (var div in divs) {
document.getElementById(div).innerHTML = divs[div];
}
(sintaxis del comentario anterior es probablemente más parecido a lo que está buscando, y tal vez es más compatible entre navegadores, pero no incluye el análisis de JSON.)
Desde JSON es sólo un subconjunto de JavaScript, sólo puede eval () de ella. JSON.parse () básicamente hace eso, pero le da la seguridad de que si '' de datos contiene un código desagradable en lugar de un objeto simple, no va a ser evaluado.
Otros consejos
En la función éxito
for (prop in data){
$('#' + prop).html(data[prop]);
}
Aquí está mi solución completa JS:
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
dataType: 'json',
data: $('#myformid').serialize(),
success: function( data ) {
for(var id in data) {
//jQuery('#' + id).html(data[id]); // This will also work
document.getElementById(id).innerHTML = data[id];
}
}
});
return false;
});