使用jQuery与Backbone发送请求时数据未追加至URL的问题
问题解决步骤
前端代码修改(Backbone.js + jQuery)
你的代码硬编码了title: "Book1",没有获取输入框的实际搜索值,这是关键词没传到URL的核心原因。同时调整模型定义位置,优化请求逻辑:
<input type="text" id="search" name="title"> <button id="searchBtn">Search</button> <script> // 把模型定义移到点击事件外,避免每次点击重复创建 var Book = Backbone.Model.extend({ urlRoot: "/tutorials/t5/todociapp/index.php/Restapi/book", idAttribute: "id", defaults: { title: null, author: null }, url: function() { return this.urlRoot + '?title=' + encodeURIComponent(this.get("title")); } }); $(document).ready(function() { $("#searchBtn").click(function() { // 获取输入框的搜索关键词 var searchTitle = $("#search").val().trim(); if (!searchTitle) { alert("请输入书名"); return; } var book1 = new Book({ "title": searchTitle }); book1.fetch({ // 移除同步请求,避免阻塞页面 success: function(model) { // 弹窗显示书名和作者 alert(`找到图书:书名 - ${model.get('title')},作者 - ${model.get('author')}`); }, error: function() { alert("搜索失败,请检查后端服务"); } }); }); }); </script>
后端CodeIgniter 3代码修改
你前端传的是GET查询参数(?title=xxx),但后端用$this->uri->segment(3)获取URI路径分段,两者不匹配导致拿不到关键词。修改后端参数获取方式:
public function book_get() { if ($this->input->server('REQUEST_METHOD') == 'GET') { // 直接获取GET查询参数title $search = $this->input->get('title'); if (empty($search)) { log_message('debug', "未传入搜索关键词"); print json_encode([]); return; } $book = $this->BookModel->getBookByTitle($search); log_message('debug', "搜索关键词:{$search}"); log_message('debug', "查询结果:" . json_encode($book)); print json_encode($book); } elseif ($this->input->server('REQUEST_METHOD') == 'POST') { log_message('debug', "HEYYYYY POST"); $data = $this->decode_data($this->input->raw_input_stream); $title = $data['title'] ?? ''; $author = $data['author'] ?? ''; $addBook = $this->BookModel->addBookToDB($title, $author); echo json_encode($addBook); } }
额外注意事项
- 确保
BookModel->getBookByTitle()方法能正确查询数据库,返回包含id、title、author字段的数组/对象 - 前端用
encodeURIComponent对关键词编码,避免特殊字符导致请求错误 - 后端增加关键词为空的判断,避免无效数据库查询
内容的提问来源于stack exchange,提问作者Kavishka Rajapakshe
相关产品推荐
相关产品推荐

