jquery AJAX and json format

前端 未结 4 1404
有刺的猬
有刺的猬 2020-11-30 09:00

I have a webservice that expects to receive json, like so:

{\"first_name\":\"test\",\"last_name\":\"teste\",\"email\":\"moi@someplace.com\",\"mobile\":\"+44          


        
4条回答
  •  春和景丽
    2020-11-30 09:05

    You aren't actually sending JSON. You are passing an object as the data, but you need to stringify the object and pass the string instead.

    Your dataType: "json" only tells jQuery that you want it to parse the returned JSON, it does not mean that jQuery will automatically stringify your request data.

    Change to:

    $.ajax({
            type: "POST",
            url: hb_base_url + "consumer",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                first_name: $("#namec").val(),
                last_name: $("#surnamec").val(),
                email: $("#emailc").val(),
                mobile: $("#numberc").val(),
                password: $("#passwordc").val()
            }),
            success: function(response) {
                console.log(response);
            },
            error: function(response) {
                console.log(response);
            }
    });
    

提交回复
热议问题