0

Until now I was using this code to post data from within a colorbox window until I ran into encoding errors, data being submitted as "ΞΞΧΑΩΞΞ" instead of 'ΔΙΧΡΩΜΟ':

$("#productadd").submit(function(){
  $.post(
  $(this).attr('action'),
  $(this).serialize(),
  function(data){
    alert('Product added to cart!');  
    $().colorbox.close();
  }
);

After some searching I decided to change my code to this so I can set the encoding when posting but I need some help to complete it:

$.ajax({
    type: "POST",
    url: $(this).attr('action'),
    contentType: "application/json; charset=iso-8859-7",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        alert('Product added to cart!'),  
        $().colorbox.close(),
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (xhr, textStatus, errorThrown) {
        $("#error").html(xhr.responseText);
    }
});

but none of the calls inside success: are made, with the page being redirected to the url in form action and neither the alert or $().colorbox.close() are being called whereas, with the previous code, it used to submit in the same window (without redirectiong to the action url) and showing the alert and finally, closing the colorbox window. Any suggestions?

4

2 回答 2

0

您必须通过阻止它执行默认操作来阻止正常的表单提交,否则它将作为正常的表单提交执行重定向到表单的 url。

$("#productadd").submit(function(e){
e.preventDefault();
$.ajax({
    type: "POST",
    url: $(this).attr('action'),
    contentType: "application/json; charset=iso-8859-7",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        alert('Product added to cart!'),  
        $().colorbox.close(),
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (xhr, textStatus, errorThrown) {
        $("#error").html(xhr.responseText);
    }
});
});
于 2012-07-12T10:11:40.457 回答
0

我相信这可以解决您提交表单的问题

$("#productadd").submit(function(event){
event.preventDefault(); // prevent submission of the form and send ajax
  $.post(
  $(this).attr('action'),
  $(this).serialize(),
  function(data){
    alert('Product added to cart!');  
    $().colorbox.close();
  }
);

至于编码,它可能取决于您获得该结果的浏览器编码,请尝试更改为其他希腊编码或 UTF-8。

于 2012-07-12T10:14:35.890 回答