Why does jquery $.ajax remove line breaks in data and $.get doesn't?

I call the same PHP script using $.ajax and $.get and get two different results.

$.ajax strips line breaks from data passed through the function while $.get doesn't.

I've tried explicitly setting the dataType to text and html with no luck. Most of the parameters for $.get default to the same in $.ajax.

http://api.jquery.com/jQuery.ajax/

Is this a bug?

Here is the exact code I use:

    $.get("lib/ajax_scripts/set-product-value.php", { input_id: input_id, val:value });

    $.ajax({
            url:"lib/ajax_scripts/set-product-value.php",
            type:'GET',
            data:'input_id='+input_id+'&val='+value});

Below is code anyone can try who has access to PHP enabled server and firebug. Look at the firebug response for each request, you will see that <br /> are added to the $.get and not to $.ajax.

ajaxtest.html

<form method="GET" onsubmit="return false">
    <textarea id="data" name="data">a
        b
        c</textarea>
    <input type="submit" value="Submit" id="submit">        
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$('#submit').click(function(){
   var data = $('#data').val();

   $.get("data.php", { data: data });


   $.ajax({
        url:"data.php",
        type:'GET',
        data:'data='+data});

});   
</script>

data.php

<?php  echo nl2br($_GET['data']); ?>

$ Ajax returned text that were missing line breaks when I appended it to my html. Since I wanted to save the formatting, I had to put tags in it. So I used the string function replace like this:

var part1 = /n/g;

var newc_data = old_data.replace(part1,"< br >") ;

This is probably a good reason to avoid text as a format. But in my case I want to write some intelligence to convert text to json.


You should get the same results. According to the docs for jQuery.get:

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

Moreover, if you look at the jQuery source code, you can clearly see that .get is just a wrapper for .ajax :

jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
    // shift arguments if data argument was omitted
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = undefined;
    }

    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
};
});

Are you sure you aren't passing other parameters to jQuery.ajax ? You might want to post the code you are using for each of them, to see if there is something else going on here.

链接地址: http://www.djcxy.com/p/8796.html

上一篇: 未定义的方法`访客'的Rails 3分贝:迁移

下一篇: 为什么jquery $ .ajax删除数据中的换行符,$ .get不是?