PHP Learning notes-php interaction with JavaScript

Source: Internet
Author: User
Tags html comment php language

Reprint please indicate the source:
http://blog.csdn.net/hai_qing_xu_kong/article/details/51814192
This article is from: "Gu Linhai's Blog"

Objective

Top two notes PHP learning notes-php interaction with Web pages 1 and PHP Learning notes-php interaction with Web pages 2 the interaction between PHP and the Web, JavaScript has been widely used in web systems, So the next thing to note is PHP's interaction with JavaScript.

Understanding JavaScript
JavaScript是由Netscape Communication Corporation(网景公司)开发的,是一种基于对象和事件驱动并具有安全性能的解释型脚本语言。它不但可用于编写客户端的脚本程序,由Web浏览器解释执行,而且还可以编写在服务器端执行的脚本程序,在服务器端处理用户提交的信息并动态地向浏览器返回处理结果。

JavaScript is a popular scripting language for creating Web effects, which is interpreted by the client browser and can be applied to PHP, ASP, JSP and ASP. In the meantime, the most popular Ajax is based on JavaScript, so mastering and applying JavaScript is very important to the developers of the Web site.

JavaScript is primarily used in the following areas:

    • Add JavaScript script code in the webpage, can make the webpage has the function of dynamic interaction, facilitate the communication between the website and the user, respond to the user's operation in time, make an immediate check on the submitted form, such as verifying whether the form element is empty, verifying whether the form element is numeric, checking whether the form element is typed incorrectly, etc.
    • The use of JavaScript script to create Web effects, such as dynamic menus, floating ads, and so on to add gorgeous dynamic effects, so that the content of the Web page more rich and lively.
    • Apply JavaScript scripts to create complex web content, such as opening a new window to load a Web page.
    • Applying JavaScript scripts can produce different responses to different events of the user.
    • Apply JavaScript to create a wide variety of images, text, mouse, animations, and page effects
    • Use JavaScript to make some small games.
JavaScript basics

JavaScript has 6 main data types, as shown in the following table:

Data Type Description Example
String type Use one or more characters enclosed in single or double quotation marks such as "PHP", "I like study php" and so on
Numeric type include integers or floating-point numbers (numbers that contain decimal points or scientific notation) such as-128, 12.9, 6.98E6, etc.
Boolean type Boolean constants have only two states, that is, true or false such as Event.returnvalue=false
Object type Use to specify the objects used in the JavaScript program such as Web Form elements
Null value You can clear the contents of a variable by assigning a null value to a variable such as A=null
Undefined Indicates that the variable has not been assigned a value such as Var a



A variable is a named storage unit in a program, and its main function is to provide a container for data operations to hold information. Before using variables, you must define the naming rules of variables, the declaration methods of variables, and the scope of variables.

1. Naming rules for variables
The naming rules for JavaScript variables are as follows:

    • Must start with a letter or underscore, in the middle can be a number, a letter, or an underscore
    • Variable names cannot contain symbols such as spaces or plus signs, minus signs, and so on.
    • The variable names of JavaScript are strictly case-sensitive. For example, user and user represent two different variables.
    • You cannot use keywords in JavaScript.

2. Declaration and assignment of variables

在JavaScript中,一般使用变量前需要先声明变量,但有时变量可以不必先声明,在使用时根据变量的实际作用来确定其所属的数据类型。所有的JavaScript变量都由关键字var声明。

The syntax is as follows:

varvariable;

You can also assign a variable to a variable while declaring it:

varvariable=11;

The following rules are followed when declaring variables:

You can declare multiple variables at the same time using a keyword VAR, for example:

i,j;

You can assign a value to a variable while declaring it, that is, initialization, for example:

i=1;j=100;

If a variable is declared only and is not assigned a value, its value defaults to undefined


In JavaScript, there are two kinds of annotation methods used:

1. Single-line Comment
Single-line comments are identified using "//". The text after the "//" symbol is not interpreted by the program. For example:

//这里是程序代码的注释

2. Multi-line comments
Multiline comments Use the "/... /"for identification. "/... /"The text after the symbol is not interpreted by the program to execute. For example:

/*这里是多行程序注释*/

3, the beginning of the HTML comment recognition <!-- JavaScript can also recognize the beginning of the HTML comment “<!--” , JavaScript will consider it as a single-line comment end, such as the use of "//". However, JavaScript does not recognize the end of an HTML comment “-->” .

Custom functions

A custom function is a program unit that is named and written by the user to implement a specific function. Custom functions used by the user must be declared in advance and cannot be directly used with custom functions that have not been declared.

JavaScript uses function to define functions in the following syntax format:

function 函数名([参数]){    returnvar;}

For example:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-type" Content="text/html; charset=gb2312 " />    <title>PHP Language Basics</title></head><body><script language="JavaScript">  function add(A, B){return a+b;    } document.write ("2+6="+add (2,6)); Alert ("running result:"+add (2,6));            </script> <?phpheader ("content-type:text/html; charset=gb2312 "); ?> </body></html>

Operation Result:

JavaScript Process Control Statement condition statement

Conditional control statements consist of two types: one is an IF condition statement and the other is a switch multi-branch statement. In JavaScript, you can use a single if condition statement, or you can use two or multiple-choice if condition statements

1. If condition statement

The IF statement is the most basic and commonly used conditional control statement. Determine whether a statement is executed by judging the value of the conditional expression to true or false.

The syntax format is as follows:

if(条件表达式){      语句块 }

In an If statement, the statement in the statement block executes only if the value of the conditional expression is true, otherwise the statement block is skipped and other program statements are executed. Where the curly brace "{}" is used to make multiple statements into a block of statements as a whole to be processed. If there is only one statement in the statement block, you can omit the curly braces. In general, it is recommended that you do not omit curly braces to avoid program errors.

The If...else statement is also the standard form of the IF statement, which is a two-branch conditional statement.

if(条件表达式)     {         语句块1;     }     else    {         语句块2;    }

In the If...else statement, when the value of the conditional expression is true, the statement in statement Block 1 is executed, and when the value of the conditional expression is false, statement block 1 is skipped and the statement in statement Block 2 is executed.

2. Switch Branch statement

Although it is possible to use an if statement to implement a multi-branch conditional statement, using the IF multi-branch conditional statement can reduce the execution efficiency of the program if the selection of branches is more than the case. The switch statement in JavaScript can improve the speed of the program by selecting the statement block that is executed against the given expression or different values of the variable.

switch(表达式或变量){     case 常量表达式1:     语句块1;     break;     case常量表达式2:     语句块2;     break;      …case常量表达式n:    语句块n;    break;     default:    语句块n+1;    break
Looping statements

A For statement is a common loop control statement. In the For statement, you can apply a loop variable to clarify the number of loops and the specific loop condition. The For statement typically uses a variable as the counter to perform the loop, which is called a loop variable.

The syntax format is as follows:

for (初始化循环变量;循环条件;确定循环变量的改变值){    语句块; }

The parentheses in the For statement contain 3 parts:

    1. Initialize the loop variable: the function of the expression is to declare the loop variable and initialize the assignment. The loop variable can also be declared and assigned before the for statement.
    2. Loop condition: The expression is a conditional expression based on a loop variable, and if the return value of the conditional expression is true, the statement block inside the loop body is executed. This expression is re-judged when the statement in the loop body is finished, until the loop is terminated when the return value of the conditional expression is false.
    3. Determine the change value of the loop variable: The conditional expression is used to manipulate the change value of the loop variable. This expression is executed every time a statement in the body of the loop is executed, before the loop condition is judged.

Note: The For statement can use the break statement to terminate the execution of the loop statement. The break statement terminates the current loop statement by default.

Jump statement

A jump statement exits a loop directly at a specified position in the loop body of a loop control statement or when a certain condition is met. JavaScript jump statements are divided into break statements and continue statements.

1. Break statement
The break statement is used to terminate the program behind it and jump out of the loop, or end the switch statement. The syntax format is as follows:

break;

2. Continue statements
The continue statement has a different effect than the break statement. The continue statement simply jumps out of the loop and immediately goes to the next loop, and the break statement ends the loop after jumping out of the loop.
The syntax format is as follows:

continue;
JavaScript events

JavaScript is an object-based language. One of its most basic features is the use of event-driven. Events are signals generated when certain actions occur, and these events can occur at any time. The action that causes an event is called a trigger event, for example, when the mouse pointer passes through a button, the user clicks a link, the user selects a check box, the user enters some information in the text box, and so on, the corresponding event is triggered. The events are described in tabular form below.

Invoking JavaScript scripts in PHP

1. Apply JavaScript script to verify that the form element is empty:

<html><head>    <meta http-equiv="Content-type" Content="text/html; charset=gb2312 ">    <title>Apply a JavaScript script to verify that the form element is empty</title></head><script language="javascript" >  function mycheck() {if (myform.user.value = = "") {al ERT ("User name cannot be empty!!            ");            Myform.user.focus (); return        false; } if (myform.pwd.value = = "") {alert ("User password cannot be empty!!            ");            Myform.pwd.focus (); return        false; }    }            </script><body><form  name  = "MyForm"  method  = "POST"  action  = "" ;     <table Width="532" height="183" align="Left"  cellpadding="0" cellspacing="0" bgcolor="#CCFF66"  Background="Images/bg.jpg">                   <tr>            <TD Height=" colspan" = "2" align= "Center" >&nbsp;</td>        </tr>        <tr>            <TD Width="249" height=" align" =  "Center">&nbsp;</td>            <TD Width="281" align="Left">User name:<input name="user" type="text" id=" User " size="> <br><br>Secret &nbsp;&nbsp; Code:<input name="pwd" type= "password" id="pwd " size="> "            </td>        </tr>        <tr>            <TD Height=" align" = "Center">&nbsp;</td>            <TD Height=" align" = "Center">                <input type="Submit" name="Submit" OnClick ="return MyCheck ();" Value="Login">&nbsp;<input type="reset" name= "Submit2" value="Reset" >            </td>        </tr>    </table></form> <?phpheader ("content-type:text/html; charset=gb2312 "); ?> </body></html>

(1) in the above code, an onclick mouse click event is added to the form element of the login button, and the Custom Function MyCheck () is called, and the code is as follows:

type="submit" name="submit" onClick="return mycheck();"value="登录">;

(2) <form> apply a function outside the form element to define a MyCheck () to verify that the form element is empty, and in the MyCheck () function, apply the IF condition statement to determine whether the user name and password submitted by the form are empty, and if it is empty, the custom function is as follows:

function mycheck() {        if"") {            alert("用户名称不能为空!!");            myform.user.focus();            returnfalse;        }        if"") {            alert("用户密码不能为空!!");            myform.pwd.focus();            returnfalse;        }    }

Operation Result:

PHP Learning notes-php interaction with JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.