weixin_33725126 2015-08-31 15:46 采纳率: 0%
浏览 39

调用jQuery ajax函数

Please bear with me; I've been battling with this for days.

I have a little bit of jQuery code in my jQuery(document).ready function as follows:

        jQuery(document).ready(function($) {
        jQuery.post(ajaxurl, data, function(response) {
          alert(response);
        });
    });

I have a text input field which I want sent to my Ajax function (using the Wordpress API)

    <input type="text" name="input" id=input onkeydown="if (event.keyCode == 13) {send_message(this.value);}">

If the user presses the key, the text is sent to the javascript 'send_message' function (below).

function send_message(value){
  data[txt]=value;
  jQuery.post(ajaxurl, data, function(response) {
    alert(response);
  });
}

BAsically, I've added a 'txt' key/value pair to my data object and I now want this submitted to my ajax function.

The 'document ready' part works fine, but I can't get it to accept the changed data object.

As you can probably tell, I'm not following the logic behind the jQuery code very well.

  • 写回答

2条回答 默认 最新

  • weixin_33675507 2015-08-31 15:56
    关注

    The data parameter in your function is not initialized. You should probably see a javascript error if you inspect your page using chrome or firefox.

    Basically the data parameter in jquery's post function accepts either a serialized form query string or JSON string/object.

    Also, please check the api: http://api.jquery.com/jquery.post/

    Try below modified code:

    function send_message(value){
        var data={txt:value};
          jQuery.post(ajaxurl, data, function(response) {
            alert(response);
          });
        }
    
    评论

报告相同问题?