AJAX响应返回当前页面

时间:2015-10-27 23:07:47

标签: ajax zend-framework

我现在正在寻找一个类似的问题,但是没有一个解决方案适合我(而且我找不到完全相同的问题)。

首先,我正在开发的网站是在Zend Framework上运行的。我怀疑它与这个问题有关。

我想制作一个非常基本的AJAX功能,但由于某种原因,我的响应总是等于当前页面的html。我不需要任何Zend的功能,我需要实现的功能(我更喜欢它们)与框架分开工作。

出于测试目的,我尽可能简单,但我找不到错误。我有一个页面" test.php"它只有一个触发ajax调用的链接。以下是此调用的外观:

$('.quiz-link').click(function(e){
    e.preventDefault();
    $.ajax({
        URL: "/quiz_api.php",
        type: "POST",
        cache: false,
        data: {
            'test': 'test'
        },
        success: function(resp){
            console.log(resp);
        },
        error: function(resp){
            console.log("Error: " + reps);
        }
    }); 
});

这个quiz_api.php只是:

<?php
    echo "This is a test";
?>

当我点击链接时,我会获得当前页面的整个HTML。 &#34;这是一个测试&#34;在那里找不到。我也收到错误:&#34;主线程上的同步XMLHttpRequest因其对最终用户体验的不利影响而被弃用。如需更多帮助,请查看http://xhr.spec.whatwg.org/。&#34;

我认为它与此HTML响应中包含的JS文件有关,但我也尝试过设置&#34; async:true&#34;它没有帮助。

我想避免使用Zend Framework函数来完成这项任务,因为我对它并不熟悉,甚至制作一个简单的控制器听起来也很痛苦。相反,我想找出造成这种行为的原因,看看是否可以改变。

PS:我还尝试将quiz_api.php移动到另一个域,但它没有改变任何内容。

1 个答案:

答案 0 :(得分:1)

我知道它可能是一个较旧的代码,但它的工作原理,简单且适应性强。这就是我想出来的。希望它适合你。

//Here is the html
<a href="#" id="test" onclick="test()">Link Test</a>
<div id="test_div"></div>

function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
    if(hr.readyState == 4 && hr.status == 200){
        var return_data = hr.responseText;
            console.log(return_data);
            document.getElementById('test_div').innerHTML = return_data;
    }else{
        document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
    }
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}

您可以使用document.write更改整个页面,而不是更改单个“div”s

相关问题