将字符串从php传递给js函数

问题描述 投票:-1回答:2

无法将字符串从php页面传递到另一个页面的js函数。

检查添加项是否存在于数组中后显示消息。我已尝试在警告声明中添加引号或不引用1.在alert语句中使用引号,javascript未转换语句但只是直接显示它。 2.在警告声明中没有引号,Chrome表示如果没有引号则会出错。

add_product.php(js函数):

function add_to_cart(){
  jQuery('#modal_errors').html("");
  var error='';
  var available =$("#size option:selected").data("available");
  var quantity = jQuery('#quantityInput').val();
  {document.getElementById("available").value = available;
     var data = jQuery('#add_product_form').serialize();
     jQuery.ajax({
        url : 'cart.php',
        method : 'post',
        data : data,
        success: function(){
            alert("<?php echo $respMsg; ?>");
            location.reload();},
        error : function(){alert("something wrong");}
                });
        return;
}

cart.php:

if ($duplicate==false){
    $respMsg="The item is in cart now.";
} else {
    $respMsg="You have added the item twice.";
}

我希望js msgbox弹出窗口显示其中一条php消息,但实际输出要么是告诉语法错误要么是显示代码字符串。

javascript php json ajax
2个回答
1
投票

如果你想打印你的回复,那么你不能说alert("<?php echo $respMsg; ?>");

您需要做的是实际获取回调中的数据并提醒该数据。

success: function(data){
            alert(data);
            location.reload();
},

1
投票

首先,你需要使用一个函数到cart.php返回$respMsg结果,然后使用来自de jQuery.ajax函数的data响应来提醒消息:

jQuery.ajax({
   url : 'cart.php',
   method : 'post',
   data : data,
   success: function(data){
              alert("Message: " + data);
              location.reload();
            },
   error : function(){
             alert("something wrong");
            }
});

有关data响应和success响应的更多信息,请访问jQuery manual

编辑:你还需要在这里删除花括号:

{document.getElementById("available").value = available;

它可能会导致JS语法错误。

© www.soinside.com 2019 - 2024. All rights reserved.