如何使用Ajax调用来检索数据

问题描述:

我喜欢用Ajax调用来检索字符串,但我一直在我的响应中获取整个html页面。如何使用Ajax调用来检索数据

什么是刚才检索字符串的方式?

$.ajax({ 
        url: '{$domainpath}{$language}/reservations/updatestartdates', 
        data: {property:property,stayduration:stayduration}, 
        type: 'POST', 
        dataType: 'json' 
       }).done(function(response){ 
        alert(response); 
       }); 

private function updateAvailableStartDates(){ 
    if(isset($_POST['property']) && !empty($_POST['property']) && isset($_POST['stayduration']) && !empty($_POST['stayduration'])){ 
     $property = $_POST['property']; 
     $stayduration = $_POST['stayduration']; 
    } 
    //handle code 

    echo json_encode('only this string'); 
} 
+1

如果是AJAX请求,您需要echo _only_字符串 – 2013-02-26 08:39:12

+0

@DipeshParmar这有什么好处? – 2013-02-26 08:41:28

+0

在输出页面内容之前放置你的更新函数,并在'echo'后添加一个'exit;',这样它就会在POST请求匹配时退出等。 – adeneo 2013-02-26 08:43:05

通常,打印JSON后立即退出是一个好主意,以防止内容(可能是\ n)打破响应。

echo json_encode('only this string'); 
exit(); 
+0

这个确实对我有用!我也必须改变我的编码,像这样'echo json_encode(array('success'=> $ string));'并用'availableDates = response.success.split(',');' – 2013-02-28 08:34:18

它会检索所有从url: '{$domainpath}{$language}/reservations/updatestartdates'输出,

所以,如果你想字符串,则只有echo在您的服务器网页字符串(删除所有HTML输出)

也会改变echo json_encode('only this string');echo json_encode(array('only this string'));

我认为你的函数发送了启用布局模式的响应,以便字符串带有包装布局。可能是您需要禁用控制器中的调用函数 (url: '{$domainpath{$language}/reservations/updatestartdates')的布局。