【问题标题】:Having empty string from returning in PHP在 PHP 中返回空字符串
【发布时间】:2016-10-04 03:37:51
【问题描述】:

当我在文本框中使用/ 之类的字符时,我会在response 中返回一个empty string。我可以轻松地在我的 html 中检查 empty string,但我的问题是如何避免在我的 php 代码中发送空字符串?

$("#search").keyup(function(){
    var newVal = $(this).val();
    if(!newVal==""){
         $.ajax({
              type : 'get',
              dataType: 'html',
              url : '/searchpost/' + newVal , 
              success : function(response) {
                   console.log(response);
              }
         });
    }
});

public function searchpost() {

        $q = $this->uri->segment(3);
        if(!$q) die();

        $string = trim(strip_tags($q));
        $db_string = urldecode($string);

        $this->db->select("postID, post_title, post_url, post_status");
        $this->db->like("post_title", $db_string);
        $this->db->or_like("post_url", $db_string);

        $posts = $this->db->get('posts', 10);

        if(!count($posts->result())) {
            die('Nothing to display');
        }

        ?>

        <ul>
        <?php 
        foreach($posts->result() as $m) : 
            if($m->post_status != 'active' OR empty($m->post_title)) continue;
        ?>
        <li>
            <a href="<?php echo '/posts/'.$m->postID.'/'.url_title($m->post_title); ?>" class="url-post-title" style="font-size:14px;"><?php echo $m->post_url; ?></a>
            </a>
        </li>
        <?php endforeach; ?>
        </ul>

        <?php 

    }

【问题讨论】:

  • / 用作转义字符,使用控制台日志和 var_dump 检查您发送和接收的内容。
  • @Aschab 控制台打印出“(空字符串)”
  • console.log($(this).val()) 给你空字符串?
  • @Aschab 不...响应。输入值正确

标签: php mysql sql arrays


【解决方案1】:

您可以更改您的 js 函数并在发送请求之前使用 encodeURIComponent 对值进行编码:

$("#search").keyup(function(){
    var newVal = $(this).val();
    if(newVal !== undefined && newVal.length > 0){
         $.ajax({
              type : 'get',
              dataType: 'html',
              url : '/searchpost/' + encodeURIComponent(newVal) , 
              success : function(response) {
                   console.log(response);
              }
         });
    }
})

然后您可能必须在 php 函数中处理现在 url 编码的值。

所以代替:

$db_string = urldecode($string);

使用rawurldecode

$db_string = rawurldecode($string);

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2017-07-03
    相关资源
    最近更新 更多