php采用ajax數(shù)據(jù)提交post與post常見(jiàn)方法總結(jié),ajaxpost
Jun 13, 2016 am 09:21 AMphp采用ajax數(shù)據(jù)提交post與post常見(jiàn)方法總結(jié),ajaxpost
本文實(shí)例講述了php采用ajax數(shù)據(jù)提交post與post常見(jiàn)方法。分享給大家供大家參考。具體方法如下:
在很多情況下我們使用ajax是不會(huì)有什么問(wèn)題的,但有時(shí)會(huì)碰到ajax數(shù)據(jù)提交post不完整的問(wèn)題,這里舉例給大家分析一下。
下邊是一個(gè)標(biāo)準(zhǔn)的ajax請(qǐng)求代碼,正常情況下是不會(huì)有任何問(wèn)題的,但是,在特定情況下就會(huì)出現(xiàn)問(wèn)題,比如,username=fdas&321的時(shí)候,或者參數(shù)值中出現(xiàn)了&符號(hào),經(jīng)過(guò)了N多遍測(cè)試,發(fā)現(xiàn)數(shù)據(jù)都傳輸了,但是打印出來(lái)數(shù)據(jù)是半截,最后仔細(xì)觀察頭信息發(fā)現(xiàn)傳輸?shù)念^不對(duì),問(wèn)題定位到了js上,發(fā)現(xiàn)字符串拼接的方式會(huì)造成這種問(wèn)題username=fdas&321&password=password這樣就是錯(cuò)誤了的。所以我們需要把傳輸?shù)臄?shù)據(jù)變成 {username:username,passsword:password}這種json格式即可避免問(wèn)題!
示例代碼如下:
復(fù)制代碼 代碼如下:
$(".submit").bind('click',function(){
var username = $("input[name='username']").val();
$.ajax({
url:"post",
type:"post",
dataType:"json",
data:"username="+username+"&password="+password,
timeout:5000,
error:function(){
alert(1)
},
success:function(){
}
})
})
補(bǔ)充:四種常見(jiàn)的 POST 提交數(shù)據(jù)方式
① application/x-www-form-urlencoded
這應(yīng)該是最常見(jiàn)的 POST 提交數(shù)據(jù)的方式了。瀏覽器的原生 form 表單,如果不設(shè)置 enctype 屬性,那么最終就會(huì)以 application/x-www-form-urlencoded 方式提交數(shù)據(jù)。請(qǐng)求類似于下面這樣(無(wú)關(guān)的請(qǐng)求頭在本文中都省略掉了):
復(fù)制代碼 代碼如下:
POST http://www.bkjia.com HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=utf-8
?
title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3
首先,Content-Type 被指定為 application/x-www-form-urlencoded;其次,提交的數(shù)據(jù)按照 key1=val1&key2=val2 的方式進(jìn)行編碼,key 和 val 都進(jìn)行了 URL 轉(zhuǎn)碼。大部分服務(wù)端語(yǔ)言都對(duì)這種方式有很好的支持。例如 PHP 中,$_POST['title'] 可以獲取到 title 的值,$_POST['sub'] 可以得到 sub 數(shù)組。
很多時(shí)候,我們用 Ajax 提交數(shù)據(jù)時(shí),也是使用這種方式。例如 JQuery 和 QWrap 的 Ajax,Content-Type 默認(rèn)值都是「application/x-www-form-urlencoded;charset=utf-8」。
② multipart/form-data
這又是一個(gè)常見(jiàn)的 POST 數(shù)據(jù)提交的方式。我們使用表單上傳文件時(shí),必須讓 form 的 enctyped 等于這個(gè)值。直接來(lái)看一個(gè)請(qǐng)求示例:
復(fù)制代碼 代碼如下:
POST http://www.bkjia.com HTTP/1.1
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA
?
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="text"
?
title
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png
?
PNG ... content of chrome.png ...
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--
這個(gè)例子稍微復(fù)雜點(diǎn)。首先生成了一個(gè) boundary 用于分割不同的字段,為了避免與正文內(nèi)容重復(fù),boundary 很長(zhǎng)很復(fù)雜。然后 Content-Type 里指明了數(shù)據(jù)是以 mutipart/form-data 來(lái)編碼,本次請(qǐng)求的 boundary 是什么內(nèi)容。消息主體里按照字段個(gè)數(shù)又分為多個(gè)結(jié)構(gòu)類似的部分,每部分都是以 --boundary 開(kāi)始,緊接著內(nèi)容描述信息,然后是回車,最后是字段具體內(nèi)容(文本或二進(jìn)制)。如果傳輸?shù)氖俏募€要包含文件名和文件類型信息。消息主體最后以 --boundary-- 標(biāo)示結(jié)束。關(guān)于 mutipart/form-data 的詳細(xì)定義,請(qǐng)前往 rfc1867 查看。
這種方式一般用來(lái)上傳文件,各大服務(wù)端語(yǔ)言對(duì)它也有著良好的支持。
上面提到的這兩種 POST 數(shù)據(jù)的方式,都是瀏覽器原生支持的,而且現(xiàn)階段原生 form 表單也只支持這兩種方式。但是隨著越來(lái)越多的 Web 站點(diǎn),尤其是 WebApp,全部使用 Ajax 進(jìn)行數(shù)據(jù)交互之后,我們完全可以定義新的數(shù)據(jù)提交方式,給開(kāi)發(fā)帶來(lái)更多便利。
③ application/json
application/json 這個(gè) Content-Type 作為響應(yīng)頭大家肯定不陌生。實(shí)際上,現(xiàn)在越來(lái)越多的人把它作為請(qǐng)求頭,用來(lái)告訴服務(wù)端消息主體是序列化后的 JSON 字符串。由于 JSON 規(guī)范的流行,除了低版本 IE 之外的各大瀏覽器都原生支持 JSON.stringify,服務(wù)端語(yǔ)言也都有處理 JSON 的函數(shù),使用 JSON 不會(huì)遇上什么麻煩。
JSON 格式支持比鍵值對(duì)復(fù)雜得多的結(jié)構(gòu)化數(shù)據(jù),這一點(diǎn)也很有用。記得我?guī)啄昵白鲆粋€(gè)項(xiàng)目時(shí),需要提交的數(shù)據(jù)層次非常深,我就是把數(shù)據(jù) JSON 序列化之后來(lái)提交的。不過(guò)當(dāng)時(shí)我是把 JSON 字符串作為 val,仍然放在鍵值對(duì)里,以 x-www-form-urlencoded 方式提交。
Google 的 AngularJS 中的 Ajax 功能,默認(rèn)就是提交 JSON 字符串。例如下面這段代碼:
復(fù)制代碼 代碼如下:
var data = {'title':'test', 'sub' : [1,2,3]};
$http.post(url, data).success(function(result) {
...
});
最終發(fā)送的請(qǐng)求是:
復(fù)制代碼 代碼如下:
POST http://www.bkjia.com HTTP/1.1
Content-Type: application/json;charset=utf-8
?
{"title":"test","sub":[1,2,3]}
這種方案,可以方便的提交復(fù)雜的結(jié)構(gòu)化數(shù)據(jù),特別適合 RESTful 的接口。各大抓包工具如 Chrome 自帶的開(kāi)發(fā)者工具、Firebug、Fiddler,都會(huì)以樹(shù)形結(jié)構(gòu)展示 JSON 數(shù)據(jù),非常友好。但也有些服務(wù)端語(yǔ)言還沒(méi)有支持這種方式,例如 php 就無(wú)法通過(guò) $_POST 對(duì)象從上面的請(qǐng)求中獲得內(nèi)容。這時(shí)候,需要自己動(dòng)手處理下:在請(qǐng)求頭中 Content-Type 為 application/json 時(shí),從 php://input 里獲得原始輸入流,再 json_decode 成對(duì)象。一些 php 框架已經(jīng)開(kāi)始這么做了。
當(dāng)然 AngularJS 也可以配置為使用 x-www-form-urlencoded 方式提交數(shù)據(jù)。
④ text/xml
之前提到過(guò) XML-RPC(XML Remote Procedure Call)。它是一種使用 HTTP 作為傳輸協(xié)議,XML 作為編碼方式的遠(yuǎn)程調(diào)用規(guī)范。典型的 XML-RPC 請(qǐng)求是這樣的:
復(fù)制代碼 代碼如下:
POST http://www.bkjia.com HTTP/1.1
Content-Type: text/xml
?
?
XML-RPC 協(xié)議簡(jiǎn)單、功能夠用,各種語(yǔ)言的實(shí)現(xiàn)都有。它的使用也很廣泛,如 WordPress 的 XML-RPC Api,seo/seo.html" target="_blank">搜索引擎的 ping 服務(wù)等等。JavaScript 中,也有現(xiàn)成的庫(kù)支持以這種方式進(jìn)行數(shù)據(jù)交互,能很好的支持已有的 XML-RPC 服務(wù)。不過(guò),我個(gè)人覺(jué)得 XML 結(jié)構(gòu)還是過(guò)于臃腫,一般場(chǎng)景用 JSON 會(huì)更靈活方便。
希望本文所述對(duì)大家的PHP程序設(shè)計(jì)有所幫助。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
