开发者

URL in AJAX POST

I want to post these variables via AJAX:

       <div class="vIn" id="star">
        <div id="inner">
         <span id="1" class="disabled"></span>
         <span id="2" class="disabled"></span>
         <span id="3" class="disabled"></span>
         <span id="4" class="disabled"></span>
         <span id="5" class="disabled"></span>
         <input type="hidden" id="<?php echo $_GET['cID']?>" />
        </div>
      </div>

With this script:

$(doc开发者_开发百科ument).ready(function(){
 $('#inner span').click(function(){
     $(this).prevAll().andSelf().addClass('enabled');  
     var a = $(this).attr("id");
     var cID = $("#inner input").attr("id");
     $.ajax({
           type: "POST",
           url: "ajax/rating.php",
           data: "value=+a+&cID=+cID+",
           success: function(msg){
             alert(data);
           }
         });
     });});

On the click event, there is no alert. Am I using the right data in $.ajax? Thanks in advance.


I would strongly recommend allowing jQuery to worry about properly encoding the string:

var a = $(this).attr("id");
var cID = $("#inner input").attr("id");
$.ajax({
    type: "POST",
    url: "ajax/rating.php",
    data: {value: a, cID: cID},   // <== change is here
    success: function(msg){
        alert(msg);
    }
});

Note that I'm passing data into $.ajax as an object, not as a string. jQuery will correctly encode it for you. See the docs for details.

If you really, really want to do the encoding yourself, you have to do it explicitly:

data: "value=" + encodeURIComponent(a) + "&cID=" + encodeURIComponent(cID)

Also note that I'm alerting msg, not data, as that's what you've called the response argument to success.


There is a subtle error here...

       success: function(msg){
         alert(data);
       }

You can fix it like this...

       success: function(data){
         alert(data);
       }

There is another error here...

data: "value=+a+&cID=+cID+",

I think this should be...

data: "value=" + a + "&cID=" + cID,

If you still don't get an alert, please shout!


I'm no Javascript expert but shouldn't it be data: "value="+a+"&cID="+cID?


data: "value=+a+&cID=+cID+" is trying to concatenate the values without taking care of characters with special meaning. The URL might include, for example, a & character.

That is what it is trying to do, what it is actually doing is setting the string literal as the value. The attempt to include variables is just making them string data.

You should have:

data: { "value": a, "cID": cID }


There are a few problems with your use of $.ajax

data: "value=+a+&cID=+cID+",

'+' is the concatenation operator, what you are doing here is building the data string using the variables you set before. So you need to concat your variables with the strings "value=" etc.

eg.

data: "value="+a+"&cID="+cID,
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜