local-host 2012-10-23 14:34 采纳率: 100%
浏览 272

通过ajax发送json对象

I am creating a simple form input demo. Values are stored from a form in variables then they are put into json object and it is sent via ajax.

My Json object validates but how do I reference it in the data field in $.ajax? My code:

$(document).ready(function() {
  $('.submitForm').on('click',function(event){
event.preventDefault();

    var firstName = $('#firstName').val();
    var lastName  = $('#lastName').val();
    var phone     = $('#phoneNumber').val();
    var address   = $('#address').val();
    var $out      = $("#formResults");

    $out.append("<p>" + firstName  +' '+ lastName + "</p>" +                                       
                "<p>" + $('#phoneNumber').val() + "</p>" + 

                    //json object
                     {
                       "firstName" : "firstName", 
                        "lastName" : "lastName",
                        "phoneNumber" : "phoneNumber",
                        "address" : "address"
                       }


                         $.ajax({
                         url: 'http://localhost/xyz/markup/',
                         method:  'GET',
                         data: jsonObject
                         error: alert("error")
                         complete: alert ("complete")
                                                 });
                                     });            
                                     });

thanks!

  • 写回答

1条回答 默认 最新

  • weixin_33694620 2012-10-23 14:37
    关注
    "firstName" : "firstName",
    

    should be

    "firstName" : firstName,
                  ^---     ^---note lack of quotes
    

    and similarly for the other 3 fields.

    you're trying to do string:string, instead of string:variable.

    As well, nowhere in your code is jsonObject actually defined.

    Major note: do not build JSON text yourself. It's very risky. One single syntax error (misplaced quote usually) and the whole json object becomes invalid. You'd be better off building a normal JS data structure, then using the provided json encoding facilities to produce the json string.

    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题