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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100