简体   繁体   中英

Decode Json string in javascript

I am trying to decode a json string by using JSON.parse() however, I don't know exactly where to place the code as I'm not that familiar with JSON/Jquery.

This is the JS part:

 /* ----------------------------------------------------------- */
   /*  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;

   });

The relevant part of my 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);

This outputs the following: {"submit_message":"Bedankt voor uw bericht!","isValid":true}

How can I make sure it only shows the submit_message part in the Json string?

如果您想要的是在$ error.html(data)中显示提交消息,那么您所需要做的就是将其替换为$ error.html(data.submit_message),因为jQuery会自动将json从数据变量解析为对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM