开发者

JQuery $.post Variable Post Name

开发者 https://www.devze.com 2023-04-05 02:26 出处:网络
I\'m having an issue with the jquery post() function. I have several buttons and am using a single post function to handle all the buttons. I can\'t seem to get the variable post name to work.

I'm having an issue with the jquery post() function. I have several buttons and am using a single post function to handle all the buttons. I can't seem to get the variable post name to work.

my code is as follows:

JS

NOTE: the "editor" variable is variable that is set on init of my application and already exists in the scope of this code.

controls.find('button').live('click',function(){

     //determine what button is clicked
     var action  = this.className;

     $.post("actions.php",action: editor);
     //functions run after 开发者_StackOverflowpost
});

the variable doesn't seem to get through. When I change the variable to a string it works fine. I've also tried running the toString(); function on my action variable with no change.

any ideas would be greatly appreciated.


The data variable has to be serialized.

$.post("actions.php",{'action':action,'editor':editor});

If this was a GET, the URL would look like this:
actions.php?action=ACTION_VALUE&editor=EDITOR_VALUE


This is invalid JavaScript:

action: editor

If editor is a variable defined elsewhere in your code, then maybe you are trying to send an object:

{ action: editor }

Where the object has one property named "action" with the same value as editor. In this case:

  1. The server is sent a post body of "action=[value of editor]".
  2. Your action variable defined earlier is not used, and not sent to the server.

A post body usually takes the form of "key1=value1&key2=value2". jQuery takes an object that is translated to a post body. Such an object would look like { key1: "value1", key2: "value2" }. So your call would look like:

$.post("url.php", { key1: "value1", key2: "value2" });

Or, if you have variables defined for the values:

$.post("url.php", { key1: value1, key2: value2 });

Guessing here... maybe what you want is:

$.post("actions.php", { action: action, editor: editor });

Edit: Based on your comment, maybe this is what you want:

var postData = {};
postData[action] = editor;
$.post("actions.php", postData);

There's no object literal syntax for specifying the name of a property from a variable. You have to do that with square bracket notation as above.

0

精彩评论

暂无评论...
验证码 换一张
取 消