简体   繁体   English

jQuery $ .ajax()发布-数据到控制器中的调用方法

[英]JQuery $.ajax() post - data to call method in my Controller

I am still quite new to JQuery and am having difficulties with using the $.ajax() function. 我对JQuery还是很陌生,在使用$ .ajax()函数时遇到困难。 I am attempting to send data to controller for processing. 我正在尝试将数据发送到控制器进行处理。

Debugging the Jquery, It doesn't look the ajax is called when click on the button. 调试Jquery,当单击按钮时,看起来没有调用Ajax。

  function getGuestInfo() {
        var phone= $('#phone').val();
         $.ajax({
            type: "GET",
            url: "/RequestForms/getGuestInfo.ajx",
            data: phone,
            cache: false,

            success: function(response){
                // we have the response
                window.alert("success"+   response); 
                $('#guestName').html(response);
                $('#address').val('');
                $('#email').val('');
                },
            });
          window.alert("Call"); 
    }

the button: 按钮:

                    <input type="button" value="Call Func" onclick="getGuestInfo()"/>

Controller: 控制器:

   ## @RequestMapping(value = "/getGuestInfo.ajx", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody String getGuestInfo(
    final RequestContext requestContext, @ModelAttribute Form form) { ## Do something }

Also, In this case should I use post or get to call the method in the Jquery function? 另外,在这种情况下,我应该使用post还是get来调用Jquery函数中的方法?

Considering that you are only passing a string as your data and your Controller is expecting a Form object, your server is probably returning a "Not Found" error. 考虑到您仅传递字符串作为数据,并且Controller期望使用Form对象,因此服务器可能返回“未找到”错误。 I would recommend always adding the error event to your ajax calls so you can catch them. 我建议始终将错误事件添加到您的ajax调用中,以便您可以捕获它们。

error: function (jqXHR, textStatus, errorThrown) {
   // Do something here
},

As for passing the correct data, you'll probably want to do something like this: 至于传递正确的数据,您可能需要执行以下操作:

var dataToSend = { "phone" : phone };

Then change your data to: 然后将您的数据更改为:

data: JSON.stringify(dataToSend),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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