【问题标题】:How to retrieve data with Ajax call如何使用 Ajax 调用检索数据
【发布时间】:2013-02-11 15:18:39
【问题描述】:

我喜欢使用 Ajax 调用来检索字符串,但我的响应中不断收到整个 html 页面。

获取字符串的方法是什么?

$.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');
}

【问题讨论】:

  • 如果是 AJAX 请求,您只需要回显 字符串
  • @DipeshParmar 有什么用?
  • 将更新函数放在页面内容输出之前,并在echo之后添加exit;,这样如果POST请求匹配等则退出。

标签: php jquery ajax json call


【解决方案1】:

它将检索来自url: '{$domainpath}{$language}/reservations/updatestartdates'的所有输出,

所以如果你想要字符串,那么你的服务器页面中只有 echo 字符串(删除所有 html 输出)

还将echo json_encode('only this string'); 更改为echo json_encode(array('only this string'));

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这个确实对我有用!我还必须像这样更改我的编码'echo json_encode(array('success'=>$string));'并用 'availableDates = response.success.split(',');' 捕捉它
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2021-11-16
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 2014-09-10
      相关资源
      最近更新 更多