search
HomeWeb Front-endJS TutorialAjax retrieves data and displays it on the front-end page

This time I will bring you Ajax to obtain data and display it on the front-end page. What are the precautions after Ajax obtains data and display it on the front-end page. The following is a practical case, let's take a look.

Introduction to the main function process

Loop to obtain list data

Click on the list data to enter the details page

Click to register and a successful registration prompt box will pop up

Click on the prompt box Click the OK button to jump back to the list page

Code implementation process and explanation

##1. List page

1. When accessing the link list.php, determine whether it is the PC side or the client side

$user_agent_arr = mall_get_user_agent_arr();
if(MALL_UA_IS_PC == 1)
{
  //****************** pc版 ******************
  include_once './list-pc.php';
}
else
{
  //****************** wap版 ******************
  include_once './list-wap.php';
}
2. If it is the wap version, jump to the list-wap.php page and load list.tpl.htm Page

$pc_wap = 'wap/';
$tpl = $my_app_pai->getView(TASK_TEMPLATES_ROOT.$pc_wap.'trade/list.tpl.htm');
3, list.tpl.htm page to render template

HTML

<p>
    </p><p>
      </p><p></p>
    
  
JS

$(function()
  // 渲染模块
  {
    //请求php的url
    var TRADE_AJAX_URL = window.$ajax_domain + 'get_trade_list.php';
    //获取已经封装在list.js里面的一个对象list_item_class
    var list_item_class = require('../../../../modules/list/list.js');
    //获取模板块
    var template = inline('./list-item.tmpl');
    var list_obj = new list_item_class({
      ele : $("#render-ele"),//渲染数据到id为render-ele中
      url : TRADE_AJAX_URL,//请求数据连接
      template : template //渲染的模板
    });
  });
list-item.tmpl template content (loop List content)

<p>
  {{#each list}}
  {{#if is_enroll}}
  <a>
  {{else}}
  </a><a>
  {{/if}}
    <p>
      </p>
<p>
        <i>
        </i>
      </p>
      <p>
        </p>
<p>
          </p>
<h3 id="title">{{title}}</h3>
          <p>所属品类:{{type}}</p>
        </a></p>
        <p>
          <span>
            {{ enroll_text }} 
          </span>
        </p>
      
    
  
  {{/each}}
4. List.js performs data processing, which is only some of the methods of the object. Please write the specific method by yourself.

 _self.ajax_obj = utility.ajax_request 
({
  url : self.send_url,
  data : self.ajax_params,
  beforeSend : function()
  {
self._sending = true;
_self.$loading = $.loading
({
  content:'加载中...'
});
  },
  success : function(data)
  {
self._sending = false;
//获取数据
var list_data = data.result_data.list;
console.log(data);
//渲染前处理事件
self.$el.trigger('list_render:before',[self.$list_container,data]);
_self.$loading.loading("hide");
//是否有分页
self.has_next_page = data.result_data.has_next_page;
// 无数据处理 
if(!list_data.length && page == 1)
{
  abnormal.render(self.$render_ele[0],{});
  self.$load_more.addClass('fn-hide');
  return;
}
else
{
  self.$load_more.removeClass('fn-hide');
}
//把数据放入模板
var html_str = self.template
({
  list : list_data
});
//插入渲染列表
self.$list_container.append(html_str);
//渲染后处理事件
self.$el.trigger('list_render:after',[self.$list_container,data,$(html_str)]);
self.setup_event();
  },
  error : function()
  {
self._sending = false;
_self.$loading.loading("hide");
$.tips
  ({
content:'网络异常',
stayTime:3000,
type:'warn'
  });
  }
})
5. get_trade_list.php receives the request from the front-end page, then collects and processes the data and finally returns the data to the front-end page

// 接收参数
$page = intval($_INPUT['page']);
if(empty($page))
{
  $page = 1;
}
// 分页使用的page_count
$page_count = 5;
if($page > 1)
{
  $limit_start = ($page - 1)*($page_count - 1);
}
else
{
  $limit_start = ($page - 1)*$page_count;
}
$limit = "{$limit_start},{$page_count}";
//请求数据库的借口
$sales_list_obj = POCO::singleton ( 'pai_topic_class' );
$ret = $sales_list_obj-> get_task_list(false, '', 'id DESC', $limit);
// 输出前进行过滤最后一个数据,用于真实输出
$rel_page_count = 4;
$has_next_page = (count($ret)>$rel_page_count);
if($has_next_page)
{
  array_pop($ret);
}
$output_arr['page'] = $page;
$output_arr['has_next_page'] = $has_next_page;
$output_arr['list'] = $ret;
// 输出数据
mall_mobile_output($output_arr,false);
6. The front-end page receives the request returned by get_trade_list.php Data, so as to judge and display the contents of the database in the front page. Template output

$tpl->output();

Details page

1. Click the list page to enter the details page (detail.php)

detail. The php page receives the data from the list

//接收list传过来的参数
$topic_id = intval($_INPUT['topic_id']);
$state = $_INPUT['state'];
if (empty($topic_id)) 
{
  header("location: ".'./list.php');
}
//数据库借口
$trade_detail_obj = POCO::singleton ( 'pai_topic_class' );
$ret = $trade_detail_obj->get_task_detail($topic_id,$yue_login_id);
2. Determine whether it is the PC side or the client (similar to the list page)

3. Jump to detail-wap.php to load the template detail.tpl .htm also carries parameters

$pc_wap = 'wap/';
$tpl = $my_app_pai->getView(TASK_TEMPLATES_ROOT.$pc_wap.'trade/detail.tpl.htm');
//模板附带以下三个参数到detail.tpl.htm中
$tpl->assign('ret', $ret);
$tpl->assign('topic_id', $topic_id);
$tpl->assign('state', $state);
4. Fields in the page reference object ret

<p>
  </p><p>
</p><p>
  </p><p>
<i>
<img  src="/static/imghwm/default1.png" data-src="{ret.img}" class="lazy" alt="Ajax retrieves data and displays it on the front-end page" >
</i>
  </p> 
  <p>
</p><h3 id="ret-title">{ret.title}</h3>
<p>
  {ret.enroll_text}
</p>
  

<p>
  </p><p>
</p><h3 id="生意机会详情">生意机会详情</h3>
<p>
  </p><p>{ret.content}</p>

  

  
  <p>
  <!-- IF state = "is_enter" -->
<button>
  <span>已参加</span>
</button>
  <!-- ELSE -->
  <button>
<span>报名参加</span>
  </button>
  <!-- ENDIF -->
  </p>
5. Click the sign-up button for data processing

var _self = {};
$btn.on('click', function() {
  var data = 
  {
topic_id : {ret.id}
  }
  utility.ajax_request({
url : window.$ajax_domain+'add_task_enroll_trade.php',
data : data,
type : 'POST',
cache : false,
beforeSend : function() 
{
  _self.$loading = $.loading({
content : '发送中.....'
  });
},
success : function(data) 
{
  _self.$loading.loading("hide");
  //请求成功后显示成功报名提示框,点击报名提示框确定按钮跳回列表页面
if (data.result_data.result==1) 
{
var dialog = utility.dialog
({
  "title" : '' ,
  "content" : '提交成功,点击确定返回',
  "buttons" : ["确定"]
});
 dialog.on('confirm',function(event,args)
   {
   window.location.href = document.referrer;
   });
  return;
   }
},  
error : function() 
{
  _self.$loading.loading("hide");
  $.tips({
content : '网络异常',
stayTime : 3000,
type : 'warn'
  });
}
  });
});
I believe you have read this article You have mastered the case method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Ajax+mysq realizes the three-level linkage list of provinces and municipalities

Ajax transmits Json and xml data Detailed explanation of the steps (with code)

The above is the detailed content of Ajax retrieves data and displays it on the front-end page. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Scrapy基于Ajax异步加载实现方法Scrapy基于Ajax异步加载实现方法Jun 22, 2023 pm 11:09 PM

Scrapy是一个开源的Python爬虫框架,它可以快速高效地从网站上获取数据。然而,很多网站采用了Ajax异步加载技术,使得Scrapy无法直接获取数据。本文将介绍基于Ajax异步加载的Scrapy实现方法。一、Ajax异步加载原理Ajax异步加载:在传统的页面加载方式中,浏览器发送请求到服务器后,必须等待服务器返回响应并将页面全部加载完毕才能进行下一步操

如何使用CakePHP中的AJAX?如何使用CakePHP中的AJAX?Jun 04, 2023 pm 08:01 PM

作为一种基于MVC模式的PHP框架,CakePHP已成为许多Web开发人员的首选。它的结构简单,易于扩展,而其中的AJAX技术更是让开发变得更加高效。在本文中,将介绍如何使用CakePHP中的AJAX。什么是AJAX?在介绍如何在CakePHP中使用AJAX之前,我们先来了解一下什么是AJAX。AJAX是“异步JavaScript和XML”的缩写,是指一种在

jquery ajax报错403怎么办jquery ajax报错403怎么办Nov 30, 2022 am 10:09 AM

jquery ajax报错403是因为前端和服务器的域名不同而触发了防盗链机制,其解决办法:1、打开相应的代码文件;2、通过“public CorsFilter corsFilter() {...}”方法设置允许的域即可。

ajax传递中文乱码怎么办ajax传递中文乱码怎么办Nov 15, 2023 am 10:42 AM

ajax传递中文乱码的解决办法:1、设置统一的编码方式;2、服务器端编码;3、客户端解码;4、设置HTTP响应头;5、使用JSON格式。详细介绍:1、设置统一的编码方式,确保服务器端和客户端使用相同的编码方式,通常情况下,UTF-8是一种常用的编码方式,因为它可以支持多种语言和字符集;2、服务器端编码,在服务器端,确保将中文数据以正确的编码方式进行编码,再传递给客户端等等。

Nginx中404页面怎么配置及AJAX请求返回404页面Nginx中404页面怎么配置及AJAX请求返回404页面May 26, 2023 pm 09:47 PM

404页面基础配置404错误是www网站访问容易出现的错误。最常见的出错提示:404notfound。404错误页的设置对网站seo有很大的影响,而设置不当,比如直接转跳主页等,会被搜索引擎降权拔毛。404页面的目的应该是告诉用户:你所请求的页面是不存在的,同时引导用户浏览网站其他页面而不是关掉窗口离去。搜索引擎通过http状态码来识别网页的状态。当搜索引擎获得了一个错误链接时,网站应该返回404状态码,告诉搜索引擎放弃对该链接的索引。而如果返回200或302状态码,搜索引擎就会为该链接建立索引

什么是ajax重构什么是ajax重构Jul 01, 2022 pm 05:12 PM

ajax重构指的是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更合理,提高软件的扩展性和维护性;Ajax的实现主要依赖于XMLHttpRequest对象,由于该对象的实例在处理事件完成后就会被销毁,所以在需要调用它的时候就要重新构建。

在Laravel中如何通过Ajax请求传递CSRF令牌?在Laravel中如何通过Ajax请求传递CSRF令牌?Sep 10, 2023 pm 03:09 PM

CSRF代表跨站请求伪造。CSRF是未经授权的用户冒充授权执行的恶意活动。Laravel通过为每个活动用户会话生成csrf令牌来保护此类恶意活动。令牌存储在用户的会话中。如果会话发生变化,它总是会重新生成,因此每个会话都会验证令牌,以确保授权用户正在执行任何任务。以下是访问csrf_token的示例。生成csrf令牌您可以通过两种方式获取令牌。通过使用$request→session()→token()直接使用csrf_token()方法示例<?phpnamespaceApp\Http\C

使用HTML5文件上传与AJAX和jQuery使用HTML5文件上传与AJAX和jQuerySep 13, 2023 am 10:09 AM

当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件-//File1varmyFile=document.getElementById(&#39;fileBox&#39;).files[0];varreader=newFileReader();reader.readAsText(file,&#39;UTF-8&#39;);reader.onload=myFunc;functionmyFunc(event){&nbsp;&nbsp;varres

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment