Ajax在prod服务器上不再起作用

时间:2016-10-12 07:03:08

标签: javascript ajax

我是一家小型公司的网络开发人员,决定用PHP5 / Laravel 4.2而不是Prestashop或其他任何东西制作其销售网站。该网站由另一家公司托管,我们无权在服务器上制作任何我们想要的东西。

我在6个月前制作了一个AJAX脚本,让用户知道他的运费和税费有多高。我们在法国和瑞士边境的欧洲,所以拥有这个剧本真的是必要的。它工作得很好,直到本周我想要实现另一个脚本,并发现这个脚本不再起作用了(多长时间,我不知道)。

JS:

function shippingFee()
{
        var idCountry, weight;
        weight= document.getElementById('weight').value;
        idCountry = document.getElementById("country").value;
        $.post('ajax/shippingFee',               
            {idCountry: idCountry, weight: weight},          
            function(data){
                obj = JSON.parse(data);
            $('#fee).html(obj.fee); 
            $('#total').html(obj.total);  
            $('#sub').html(obj.sub);  
            $('#promo').html(obj.promo);         
            });                     
};

这是我的路线:

Route::post('ajax/shippingFee', 'AjaxController@shippingFee');

这是我在AjaxController上的函数(不是所有内容,只是最终结果):

public function shippingFee(){

//Test values, only for this example
    $fee = 12;
    $total = 24;
    $sub = 3;
    $promo = 0;

    $res = ['fee'=>$fee, 'total'=>$total, 'sub'=>$sub, 'promo'=>$promo];
    echo json_encode($res); 
}

当我点击激活该功能的按钮时,出现此错误:

SyntaxError : unexpected token in json at position 0

如果我点击来源,我就有了JSON:

{"fee": 12, "total":24, "sub":3, "promo":0}

同样,代码在六个月前完美运行,仍然可以在localhost上运行。你对发生的事情有任何想法吗?

非常感谢。

2 个答案:

答案 0 :(得分:0)

在Post请求中指定dataType,同时检查Developer工具中的响应结果,这些结果将为您提供清晰的想法。如果您使用任何框架,如果您回显将解决问题的结果,请不要忘记调用exit(0)方法

PHP Exit method

答案 1 :(得分:0)

好的,我成功了。我不知道为什么,但我的json_encode并没有发送令人满意的json。我尝试用这个来改变我的函数的结构:

function shippingFee()
{
        var idCountry, weight;
        weight= document.getElementById('weight').value;
        idCountry = document.getElementById("country").value;

            $.ajax({
            url: "ajax/shippingFee",
            type: "Post",
            data: {'idCountry':idCountry, 'weight':weight},
            traditional: true,
            success: function (data) {

                data = JSON.stringify(eval('('+data+')'));
                var obj= JSON.parse(data);
                $('#fee).html(obj.fee); 
                $('#total').html(obj.total);  
                $('#sub').html(obj.sub);  
                $('#promo').html(obj.promo); 
                }
            });                     
};

因此,使用data = JSON.stringify(eval('('+data+')'));我说这是一个JSON。我的代码就像一个魅力。我通过观看这篇文章找到了这个解决方案:Convert object string to JSON

我试图在成功之前放置dataType:"JSON",但是当我这样做时它返回了一个错误。使用contentType:"application/json"时出现错误500.

感谢回答我的人:)