如何使用jQuery和PHP在单独的行上显示JSON响应 [英] How to display a JSON response on separate lines using jQuery and PHP
问题描述
我正在使用AJAX提交表单,并希望在页面上显示信息摘要,以便用户可以在提交之前确认信息.我无法将结果显示在多行上.关于最佳方法的任何建议吗?
I am using AJAX to submit a form, and would like to display a summary of the information on the page so that the user can confirm the information before submitting. I am having trouble getting the results to display on multiple lines. Any suggestions on the best way to do this?
这是PHP:
$return['message'] = 'First Entry: ' . $_POST['Name1'] . ' ' . 'Second Entry: ' . $_POST['Name2'] . ' ' . 'Third Entry: ' . $_POST['Name3'];
echo json_encode($return);
这是jQuery:
$("#mark-form").validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
type: "POST",
data: {
"Name1" : $('#Name1').val(),
"Name2" : $('#Name2').val(),
"Name3" : $('#Name3').val()
},
dataType: 'json',
url: './includes/ajaxtest3.php',
error: function() {alert("Error");},
success:
function(data) {
$('<div id="output2"></div>').insertAfter($('#agreement-information'));
$('#output2').html(data.message).show(500);
$('#ouput2').append(data);
},
});
return false;
},
errorPlacement: function(error,element) {
return true;
},
rules: {
"Name1": {
required: true,
}
}
});
推荐答案
您可以像这样传输JSON编码的HTML换行符:
You can transfer JSON encoded HTML newlines like this:
$return['message'] = 'First Entry: ' . $_POST['Name1'] . '<br /> ' . 'Second Entry: ' . $_POST['Name2'] . '<br /> ' . 'Third Entry: ' . $_POST['Name3'];
echo json_encode($return);
或将换行符(\ n)转换为换行符.
Or convert newlines (\n) into newline tags.
一种更好的方法是将这种处理留给客户,例如返回消息数组:
The nicer way though would be to leave that kind of processing to the client by e.g. returning an array of messages:
$return['message'] = array();
$return['message'][] = 'First Entry: ' . $_POST['Name1'];
$return['message'][] = 'Second Entry: ' . $_POST['Name2'];
$return['message'][] = 'Third Entry: ' . $_POST['Name3'];
echo json_encode($return);
然后将处理留给客户端(也许客户端稍后会希望将消息包装在段落标记中):
And leave the processing to the client (maybe the client wants the messages wrapped in a paragraph tag later on):
function(data)
{
$('<div id="output2"></div>').insertAfter($('#agreement-information'));
$('#output2').html(data.message.join('<br />')).show(500);
$('#ouput2').append(data);
}
这篇关于如何使用jQuery和PHP在单独的行上显示JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!