开发者

Need to escape white space before appending to url

开发者 https://www.devze.com 2023-03-09 08:29 出处:网络
This is the parameter portion of the string as I need it: ?parentId=PRICE&childId=%20LIST This is the parameter portion as it is (Note the missing %20):

This is the parameter portion of the string as I need it:

?parentId=PRICE&childId=%20LIST

This is the parameter portion as it is (Note the missing %20):

?parentId=PRICE&childId=LIST

Here is the function that gathers the data from two select boxes (#parentCodes and #childCodes):

            funct开发者_开发知识库ion ajaxCodeDetails(){
                $.getJSON(
                "manage-inventory-codes_codeDetails",
                {'parentId': $("#parentCodes").val(),
                    'childId': $("#childCodes").val()},
                renderDetails
            );
            }

How do I escape the result returned by val() before sending the request?


It's not a problem with jQuery but with the form. It seems that leading and trailing spaces are ignored in the option's text (apparently, this is the normal behaviour of browsers, see below):

<select name="foo">
    <option> space</option>
    <option>space </option>
</select

DEMO

but it works if they are set as values:

<select name="foo">
    <option value=" space"> space</option>
    <option value="space ">space </option>
</select>

DEMO


The HTML specification has an interesting chapter about text, in particular about white space. There is says:

In order to avoid problems with SGML line break rules and inconsistencies among extant implementations, authors should not rely on user agents to render white space immediately after a start tag or immediately before an end tag. Thus, authors, and in particular authoring tools, should write:

  <P>We offer free <A>technical support</A> for subscribers.</P>

and not:

  <P>We offer free<A> technical support </A>for subscribers.</P>

So it seems that most browsers comply to this rule and ignore those spaces.


You can use the built in encodeURI() function...

{'parentId': encodeUri($"#parentCodes").val(), 


HTML ignores leading and trailing white space within <option> tags. Replace the leading and trailing space with &nbsp; so that it is correctly interpreted as a space by the browser. You'll want to do this on the server. Depending on the language, there is likely a method that will do this conversion for you.


Try this:

function ajaxCodeDetails(){                 
    $.getJSON(                 
        "manage-inventory-codes_codeDetails",{
            'parentId': $("#parentCodes").val().replace(/^\s+/g, ""),
            'childId': $("#childCodes").val().replace(/^\s+/g, "")
        },                 
        renderDetails             
    );             
} 


You don't need to URL encode anything. jQuery will take care of this. %20 means a url encoded space. So simply put a space in your textbox and it will be properly handled. Your code is perfectly fine.

0

精彩评论

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