将值从javascript传递到servlet不在chrome中工作

时间:2013-01-25 07:07:03

标签: javascript ajax servlets

我试图通过javascript将参数传递给servlet:

function selectHandler() {
  var selection = table.getChart().getSelection()[0];
  var topping = data.getValue(selection.row, 0);
  var answer=confirm("Delete "+topping+"?");
  if(answer){
    document.location.href="/item?_method=delete&id="+topping;
    alert(topping+" has been deleted");
    location.reload();
  }
  else return false;
}

当我使用 firefox 时,这些值会传递给servlet并正常工作,因为我正在获取网址:http://XXXXXXX/item?_method=delete&id=xxxx 但是,当我使用 chrome 时,发送的网址为http://XXXXXXX/item。因为价值没有通过!!我试过window.location.href也没有改变。可能是什么问题?

1 个答案:

答案 0 :(得分:3)

你需要的是ajax调用或者说XMLHttpRequest如下:

<script type="text/javascript">
    function doAjax () {
        var request,
            selection = table.getChart().getSelection()[0],
            topping = data.getValue(selection.row, 0),
            answer=confirm("Delete "+topping+"?");

        if (answer && (request = getXmlHttpRequest())) {
            // post request, add getTime to prevent cache
            request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
            request.send(null);
            request.onreadystatechange = function() {
                if(request.readyState === 4) {
                    // success
                    if(request.status === 200) {
                        // do what you want with the content responded by servlet
                        var content = request.responseText;
                    } else if(request.status === 400 || request.status === 500) {
                        // error handling as needed
                        document.location.href = 'index.jsp';
                    }
                }
            };
        }
    }
    // get XMLHttpRequest object
    function getXmlHttpRequest () {
        if (window.XMLHttpRequest
            && (window.location.protocol !== 'file:' 
            || !window.ActiveXObject))
            return new XMLHttpRequest();
        try {
            return new ActiveXObject('Microsoft.XMLHTTP');
        } catch(e) {
            throw new Error('XMLHttpRequest not supported');
        }
    }
</script>

您也可以通过jquery轻松完成,

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
    function doAjax () {
        ...
        $.ajax({
            url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
            type: "post",
            // callback handler that will be called on success
            success: function(response, textStatus, jqXHR){
                // log a message to the console
                console.log("It worked!");
                // do what you want with the content responded by servlet
            }
        });
    }
</script>

参考:jQuery.ajax()