search
HomeWeb Front-endJS TutorialAjax method to obtain data and then display it on the page

Below I will bring you an implementation method of Ajax obtaining data and then displaying it on the page. Let me share it with you now and give it as a reference for everyone.

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 class="page-view " data-role="page-container">

    <p class="sales-list-page">
      <p id="render-ele"></p>
    </p>

  </p>

JS

$(function()
  // 渲染模块
  {
    //请求php的url
    var TRADE_AJAX_URL = window.$__ajax_domain + &#39;get_trade_list.php&#39;;
    //获取已经封装在list.js里面的一个对象list_item_class
    var list_item_class = require(&#39;../../../../modules/list/list.js&#39;);
    //获取模板块
    var template = __inline(&#39;./list-item.tmpl&#39;);

    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 class="item-wrap">
  {{#each list}}
  {{#if is_enroll}}
  <a href="./detail.php?topic_id={{id}}&state=is_enter">
  {{else}}
  <a href="./detail.php?topic_id={{id}}&state=no_enter">
  {{/if}}
    <p class="item ui-border-b" >
      <p class="img-item">
        <i class="img" style="background-image: url({{img}});">

        </i>
      </p>
      <p class="text-item">
        <p class="txt-con-1">
          <h3 id="title">{{title}}</h3>
          <p class="txt f10 color-999">所属品类:{{type}}</p>

        </p>
        <p class="txt-con-2">
          <span class="color-333 join-in ">
            {{ enroll_text }} 
          </span>

        </p>
      </p>
    </p>
  </a>
  {{/each}}
</p>

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:&#39;加载中...&#39;
});

  },
  success : function(data)
  {
self._sending = false;
//获取数据
var list_data = data.result_data.list;
console.log(data);
//渲染前处理事件
self.$el.trigger(&#39;list_render:before&#39;,[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(&#39;fn-hide&#39;);

  return;
}
else
{
  self.$load_more.removeClass(&#39;fn-hide&#39;);
}

//把数据放入模板
var html_str = self.template
({
  list : list_data
});
//插入渲染列表
self.$list_container.append(html_str);
//渲染后处理事件
self.$el.trigger(&#39;list_render:after&#39;,[self.$list_container,data,$(html_str)]);

self.setup_event();
  },
  error : function()
  {
self._sending = false;
_self.$loading.loading("hide");
$.tips
  ({
content:&#39;网络异常&#39;,
stayTime:3000,
type:&#39;warn&#39;
  });
  }
})

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[&#39;page&#39;]);



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 ( &#39;pai_topic_class&#39; );
$ret = $sales_list_obj-> get_task_list(false, &#39;&#39;, &#39;id DESC&#39;, $limit);





// 输出前进行过滤最后一个数据,用于真实输出
$rel_page_count = 4;



$has_next_page = (count($ret)>$rel_page_count);

if($has_next_page)
{
  array_pop($ret);
}

$output_arr[&#39;page&#39;] = $page;

$output_arr[&#39;has_next_page&#39;] = $has_next_page;

$output_arr[&#39;list&#39;] = $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[&#39;topic_id&#39;]);
$state = $_INPUT[&#39;state&#39;];

if (empty($topic_id)) 
{
  header("location: ".&#39;./list.php&#39;);
}

//数据库借口
$trade_detail_obj = POCO::singleton ( &#39;pai_topic_class&#39; );
$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 = &#39;wap/&#39;;
$tpl = $my_app_pai->getView(TASK_TEMPLATES_ROOT.$pc_wap.&#39;trade/detail.tpl.htm&#39;);

//模板附带以下三个参数到detail.tpl.htm中
$tpl->assign(&#39;ret&#39;, $ret);
$tpl->assign(&#39;topic_id&#39;, $topic_id);
$tpl->assign(&#39;state&#39;, $state);

4. Fields in the page reference object ret

<p class="sales-detail-page">
  <p class="item-wrap">
<p class="item-1 item">
  <p class="img-item">
<i class="img" >
<img  src="/static/imghwm/default1.png"  data-src="{ret.img}"  class="lazy"  / alt="Ajax method to obtain data and then display it on the page" >
</i>
  </p> 
  <p class="txt-item">
<h3 id="ret-title">{ret.title}</h3>
<p class="sign-in-txt color-666">
  {ret.enroll_text}
</p>
  </p>
</p>

<p class="item-3 item">
  <p class="txt-item">
<h3 id="生意机会详情">生意机会详情</h3>
<p class="txt-con f14 color-666">
  <p class="txt">{ret.content}</p>
</p>
  </p>
</p>
  </p>
  <p class="sign-name-item">
  <!-- IF state = "is_enter" -->
<button class="ui-button-submit had-joined">
  <span class="ui-button-content">已参加</span>
</button>
  <!-- ELSE -->
  <button class="ui-button-submit" id="submit">
<span class="ui-button-content">报名参加</span>
  </button>
  <!-- ENDIF -->
  </p>
</p>

5. Click the sign-up button for data processing

var _self = {};
$btn.on(&#39;click&#39;, function() {
  var data = 
  {
topic_id : {ret.id}
  }
  utility.ajax_request({
url : window.$__ajax_domain+&#39;add_task_enroll_trade.php&#39;,
data : data,
type : &#39;POST&#39;,
cache : false,
beforeSend : function() 
{
  _self.$loading = $.loading({
content : &#39;发送中.....&#39;
  });
},
success : function(data) 
{
  _self.$loading.loading("hide");
  //请求成功后显示成功报名提示框,点击报名提示框确定按钮跳回列表页面
if (data.result_data.result==1) 
{
var dialog = utility.dialog
({
  "title" : &#39;&#39; ,
  "content" : &#39;提交成功,点击确定返回&#39;,
  "buttons" : ["确定"]
});
 dialog.on(&#39;confirm&#39;,function(event,args)
   {
   window.location.href = document.referrer;
   });

  return;
   }





},  
error : function() 
{
  _self.$loading.loading("hide");
  $.tips({
content : &#39;网络异常&#39;,
stayTime : 3000,
type : &#39;warn&#39;
  });
}

  });

});

The above is what I compiled For everyone, I hope it will be helpful to everyone in the future.

Related articles:

Ajax request and Filter cooperation case analysis

How to solve the problem of arrays in AJAX requests

Ajax summary of 5 ways to solve cache

The above is the detailed content of Ajax method to obtain data and then display it on the 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool