在JavaScript中解码Json字符串
问题描述:
我想通过使用JSON.parse()
来解码json字符串,但是,我不知道确切的代码放置位置,因为我不熟悉JSON/Jquery。在JavaScript中解码Json字符串
这是JS部分:
/* ----------------------------------------------------------- */
/* Contact form
/* ----------------------------------------------------------- */
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$phone = $form.find('.form-control-phone'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
phone: $phone.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$phone.val('');
$message.val('');
}
}
);
});
return false;
});
我mailscript的相关部分:
if($isValid == true) {
$result["submit_message"] = _msg_send_ok;
} else {
$result["submit_message"] = _msg_send_error;
}
if($_POST["name"]=="" || $_POST["name"]==_def_name)
$result["error_name"] = _msg_invalid_data_name;
if($_POST["email"]=="" || $_POST["email"]==_def_email || !preg_match("#^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$#", $_POST["email"]))
$result["error_email"] = _msg_invalid_data_email;
if($_POST["message"]=="" || $_POST["message"]==_def_message)
$result["error_message"] = _msg_invalid_data_message;
$result['isValid'] = $isValid;
echo json_encode($result);
此输出以下:{"submit_message":"Bedankt voor uw bericht!","isValid":true}
我如何确保它只显示Json字符串中的submit_message部分?
答
如果你想要在$ error.html(data)中显示提交消息,那么你所需要做的就是用$ error.html(data.submit_message)替换它,因为jQuery自动从数据中解析出json变成一个对象。
如果您将'$ .post'数据类型设置为JSON,则根本不需要对其进行解码。 jQuery会为你做到这一点。检查[jQuery.post](http://api.jquery.com/jQuery.post/) – apokryfos
[JQuery解析JSON数组]可能的重复(http://*.com/questions/10463131/jquery-parsing-json - 阵列) –