JQuery - $.ajax POST does not send .data to web server

后端 未结 5 897
你的背包
你的背包 2021-01-17 18:31

I am using the JQuery $.ajax post command to invoke an ajax event on my web server:

var formParams = \"fe1=y&fe2=m&fe3=m\";

$.ajax({
    type: \'POS         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 18:45

    Your code as quoted is fine (I've tried it locally).

    My guess is that the formParams string in your question is just an example, and in reality you're doing something to generate that string on the fly, and the problem lies in that code instead.

    For instance, are you sure you're escaping characters correctly (using encodeURIComponent)? Or better yet, let jQuery deal with it, like this:

    $.ajax({
        type: 'POST',
        url: '/foo.jsp',
        async: false,
        data: {
            fe1: $("#somefield1").val(),
            fe2: $("#somefield2").val(),
            fe3: $("#somefield3").val()
        },
        complete: function(xmlRequestObject, successString){
            ymmReceiveAjaxResponse(xmlRequestObject, successString);
        }
    });
    

    If you pass in an object, jQuery will handle the URI-encoding for you. If you really want to do it yourself:

    var formParams =
        "fe1=" + encodeURIComponent($("#somefield1").val()) +
        "fe2=" + encodeURIComponent($("#somefield2").val()) +
        "fe3=" + encodeURIComponent($("#somefield3").val());
    $.ajax({
        type: 'POST',
        url: '/foo.jsp',
        async: false,
        data: formParams,
        complete: function(xmlRequestObject, successString){
            ymmReceiveAjaxResponse(xmlRequestObject, successString);
        }
    });
    

    There I haven't encoded the field names because those names don't have any special chars in them; you need to if your form names are more interesting than that.

提交回复
热议问题