开发者

javascript: hacking a string to be sent in a jQuery post (form serialization)

开发者 https://www.devze.com 2023-02-12 03:50 出处:网络
I am using serialize() in an ajax() call. However, I only want to send some fields - more specifically, I don\'t want to send the content field - as this contains a lot of verbose text - and is not ne

I am using serialize() in an ajax() call. However, I only want to send some fields - more specifically, I don't want to send the content field - as this contains a lot of verbose text - and is not needed.

I tried using $('#elem_id').serialize()

but that returned an empty array (yes 'elem_id' is the id of an element in the DOM and it does exist).

Instead, I am using $('#form_id').serialize(), which works but generates a ton of rubbish which I do not need..

Here is a sample string that is generated when I use serialize on the entire form:

rating%5Bvote_value%5D=3&blog_post%5Bcontent%5D=a-really-really-long-piece-of-text&blog_post%5Bid%5D=1

I want to implement a hack, to extract the string 'blog_post%5Bcontent%5D=a-really-really-long-piece-of-text' from the string obtained from the .serialize() method, so that I don't eat up all my bandwidth.

Can anyone help with a JS function that will rip out 'blog_post%5Bcontent%5D=a-really-really-long-piece-of-text' and splice the string back together so that I can send the shortened string to the server?

Here is my attempt:

function delete_content_param(long_str){
  var pos1 = str.indexOf("&blog_post%5Bcontent%5D=");
  alert('pos1:'+ pos1);
  var pos2 = str.indexOf("&",pos1);
  alert('pos2:'+ pos2);
}

This did not yield the result I expected (i.e. index numbers), I thou开发者_如何学Goght I'd better come in here and ask the javascript Gurus, before wasting (yet another) entire afternoon


You can filter out fields you wish to not serialize by using .not()

$("#theForm :input").not("#text1").serialize();

jsfiddle example.


You can pass an object as the data argument of jQuery's AJAX methods. So there's no need to mess around with query strings - you can simply remove an element from the object before passing it to the method.

0

精彩评论

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