XMLHttpRequest(XHR)是一个JavaScript对象,它公开了一个API,用于从运行Web浏览器的前端代码发出异步HTTP请求 - 也就是说,用于启用称为AJAX的编程技术。 XHR API是遗留API。它已被Fetch API取代。
我正在尝试使用javascript中的拖放插件来使用ajax上传文件。 DnD.on('#drop-area', { 'drop':函数(文件,el){ el.firstChild.nodeValue = '拖动一些fi...</desc> <question vote="3"> <p>我正在尝试在javascript中使用<a href="http://pascalprecht.github.com/DnD.js/" rel="nofollow">拖放插件</a>来使用ajax上传文件。 </p> <pre><code><script> DnD.on('#drop-area', { 'drop': function (files, el) { el.firstChild.nodeValue = 'Drag some files here.'; var names = []; [].forEach.call(files, function (file, i) { names.push(file.name + ' (' + file.size + ' bytes)'); var xhr = new XMLHttpRequest(); xhr.open('POST','upload.php'); xhr.setRequestHeader("Content-type", "multipart/form-data"); xhr.send(file); console.log(xhr.responseText); }); document.querySelector('#dropped-files p i').firstChild.nodeValue = names.join(', '); } }); </script> </code></pre> <p>这是 upload.php:</p> <pre><code><?php print_r($_POST); ?> </code></pre> <p>基本上我还没有编写上传文件的脚本,因为我仍在弄清楚如何访问通过 JavaScript 发送的数据。你能指导我下一步该怎么做吗?如何从 upload.php 访问文件。</p> </question> <answer tick="true" vote="10"> <p>尝试使用 <pre><code>FormData</code></pre> 代替 <pre><code>xhr</code></pre>:</p> <pre><code>var formData = new FormData(); formData.append("thefile", file); xhr.send(formData); </code></pre> <p>您可以通过以下方式访问您的文件 <pre><code>array</code></pre>:</p> <pre><code><?php var_dump($_FILES["thefile"]); ?> </code></pre> <p>查看更多:<a href="http://www.w3schools.com/php/php_file_upload.asp">http://www.w3schools.com/php/php_file_upload.asp</a></p> </answer> <answer tick="false" vote="0"> <p>PHP 代码:</p> <pre><code><?php if($_SERVER['REQUEST_METHOD'] == 'POST'){ echo $_FILES['image']['name']; } ?> </code></pre> <p>HTML 代码:</p> <pre><code><form method="post" enctype="multipart/form-data"> <input id="file-to-upload" type="file" name="file-to-upload"> <button id="btn-submit">upload</button> </form> </code></pre> <p>Javascript代码:</p> <pre><code>document.querySelector('#btn-submit').addEventListener('click' , function(ev){ ev.preventDefault(); /** * formData() representing form fields * https://developer.mozilla.org/en-US/docs/Web/API/FormData */ formData = new FormData(); /** * fileToUpload [input file] * input file has property called [files] contain 1 or multiple files * i use one file so i get 0 index file => image.files[0] */ fileToUpload = document.querySelector('#file-image'); formData.append('image' , image.files[0]); /** * XMLHttpRequest */ var xhr = new XMLHttpRequest(); xhr.open('POST' , 'page.php' , true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ console.log(this.responseText); } } xhr.send(formData); }); </code></pre> </answer> </body></html>
这让我发疯。我在 VB 中完成了这个工作,但无法让这个代码工作。将 URL 拼凑在一起可以正常工作,因为我可以输出它,然后复制地址并生成输出。
JavaScript 获取托管在另一个源上的文件大小,无需控制跨源标头
这里有一个虚拟 PDF 文件可供下载:https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf 这是在 w3.org 上托管的,所以我绝对无法控制响应头......
XMLHttpRequestUpload loadend 事件会立即触发,无论 React 中的实际上传过程如何
当我在我的 React 应用程序中调用此函数(在 try...catch 块中等待它)时,onloadend 和 onprogress 事件会立即触发,尽管实际的上传过程需要一些时间(我
从 MS Access 中的 vba 向 Azure 翻译器发出 Http 请求
我想向 api.cognitive.microsofttranslator.com/translate 发送 http 请求并发送一些文本进行翻译,但它不起作用。 我尝试这个请求: 公共子翻译() 昏暗的strU...
我一直在尝试从以下站点提取数据:https://bitinfocharts.com/comparison/activeaddresses-btc-eth-ltc.html 令人沮丧的是,没有下载按钮......
我的curl命令从XML文件发送XML数据,并将响应写入指定的路径。如何在 Node.js 中实现这一点? cd C:/test/ && curl localhost:9001 --data @ C:/test/
我在 html 页面中有以下 JavaScript 函数,该函数将两个参数发送到 JSP 页面。我尝试通过发出 GET 请求来发送参数,并且能够在 JSP 中接收它们。但当我
如何将值从 Outlook VBA 表单传递到 asmx Web 服务?
我正在尝试将文本框值从 Outlook 用户表单传递到 asmx Web 服务。我已经使用 PHP 成功完成了此操作,但现在需要使用 VBA 来完成此操作。目前该表格对
Fetch API,给我index.html,但没有给我react JS中UI的dom结构
我在reactjs上构建了一个应用程序并在内部托管,当我执行fetch API或xhr时,我只获得公共文件夹中的index.html,并且它以id = root结尾。然而它并没有给我...
当我在生产系统上执行 XHR 时,响应中的 statusText 将是一个空字符串。但是,在我们的开发系统上,statusText 将正确反映状态。 雅阁...
有什么好方法可以找出特定 $.ajax() 请求花费了多长时间? 我想获取此信息,然后将其显示在页面上的某个位置。 回答??:::: 我是 JavaScript 新手,...
PHP显示XMLHttpRequest发送的POST数据不存在?
我目前正在尝试在 XAMPP 上创建一个注册页面。我的系统的总结是,当用户单击提交按钮时,JS 通过 POST 对 php 文件执行 xmlhttprequest,上传用户的数据...
从源“http://localhost:5173”访问“...”处的 XMLHttpRequest 已被 CORS 策略阻止
我正在使用 MERN 堆栈开发一个应用程序,使用reactjs作为前端,nodejs作为后端。我已经开发了后端代码并使用邮递员进行了测试,但是在来回访问登录和其他API时...
PHP-Laravel Amazon feed XML 解析第 1 行第 1 列发生致命错误
1.02 <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd"> <Header> <DocumentVersion>1.02</DocumentVersion> <MerchantIdentifier>MYMERCHANT123</MerchantIdentifier> </Header> <MessageType>ProcessingReport</MessageType> <Message> <MessageID>1</MessageID> <ProcessingReport> <DocumentTransactionID>172210019669</DocumentTransactionID> <StatusCode>Complete</StatusCode> <ProcessingSummary> <MessagesProcessed>0</MessagesProcessed> <MessagesSuccessful>0</MessagesSuccessful> <MessagesWithError>1</MessagesWithError> <MessagesWithWarning>0</MessagesWithWarning> </ProcessingSummary> <Result> <MessageID>0</MessageID> <ResultCode>Error</ResultCode> <ResultMessageCode>5001</ResultMessageCode> <ResultDescription>XML Parsing Fatal Error at Line 1, Column 1: Content is not allowed in prolog. Content is not allowed in prolog.</ResultDescription> </Result> </ProcessingReport> </Message> </AmazonEnvelope> 这是我的错误,这是我的代码: $requestXml = '<?xml version="1.0" encoding="utf-8"?> <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd"> <Header> <DocumentVersion>1.01</DocumentVersion> <MerchantIdentifier>MYMERCHANT123</MerchantIdentifier> </Header> <MessageType>Product</MessageType> <PurgeAndReplace>false</PurgeAndReplace> <Message> <MessageID>1</MessageID> <OperationType>Update</OperationType> <Product> <SKU>56789</SKU> <StandardProductID> <Type>ASIN</Type> <Value>B0EXAMPLEG</Value> </StandardProductID> <ProductTaxCode>A_GEN_NOTAX</ProductTaxCode> <DescriptionData> <Title>Example Product Title</Title> <Brand>Example Product Brand</Brand> <Description>This is an example product description.</Description> <BulletPoint>Example Bullet Point 1</BulletPoint> <BulletPoint>Example Bullet Point 2</BulletPoint> <MSRP currency="USD">25.19</MSRP> <Manufacturer>Example Product Manufacturer</Manufacturer> <ItemType>example-item-type</ItemType> </DescriptionData> <ProductData> <Health> <ProductType> <HealthMisc> <Ingredients>Example Ingredients</Ingredients> <Directions>Example Directions</Directions> </HealthMisc> </ProductType> </Health> </ProductData> </Product> </Message> </AmazonEnvelope>'; // $requestXml = trim($requestXml); // doesn't help // $requestXml = preg_replace('/[[:^print:]]/', '', $requestXml); // $requestXml = preg_replace('/^(\xEF\xBB\xBF)/', '', $requestXml); $response = Http::withHeaders([ 'Content-Type' => 'text/xml; charset=utf-8' ])->put($url, [ 'body' => $requestXml ]); 我希望有人可以帮助我,因为我快疯了,因为几天后我无法解决这个问题,但这很重要。 我尝试了在互联网上找到的所有内容,阅读了 Stackoverflow 上的所有内容,但没有解决我的问题。 我还尝试从文件中调用它(我通过 Notepad++ 将其保存为 UTF-8) $prefixAmazon = Storage::disk('amazon')->getDriver()->getAdapter()->getPathPrefix(); $requestXml = file_get_contents($prefixAmazon . 'createFeed.xml'); 我找到了使用 Amazon SP-API 在 Laravel 中创建产品源的解决方案 (https://github.com/amazon-php/sp-api-sdk): composer require amazon-php/sp-api-sdk composer require nyholm/psr7 -W use AmazonPHP\SellingPartner\AccessToken; use AmazonPHP\SellingPartner\Model\Feeds\CreateFeedDocumentSpecification; use AmazonPHP\SellingPartner\Model\Feeds\CreateFeedSpecification; use AmazonPHP\SellingPartner\Regions; use AmazonPHP\SellingPartner\SellingPartnerSDK; use App\Models\Amazon\AmazonAuth; use Exception; use GuzzleHttp\Handler\CurlFactory; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\App; use Carbon\Carbon; use Illuminate\Support\Facades\Storage; use GuzzleHttp\Client; use AmazonPHP\SellingPartner\Api\FeedsApi\FeedsSDK; use AmazonPHP\SellingPartner\Configuration; use AmazonPHP\SellingPartner\Exception\ApiException; use AmazonPHP\SellingPartner\Exception\InvalidArgumentException; use AmazonPHP\SellingPartner\HttpFactory; use AmazonPHP\SellingPartner\HttpSignatureHeaders; use AmazonPHP\SellingPartner\ObjectSerializer; use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestInterface; use Psr\Log\LoggerInterface; use AmazonPHP\SellingPartner\OAuth; use Buzz\Client\Curl; use Nyholm\Psr7\Factory\Psr17Factory; use Psr\Log\NullLogger; public function getAccessToken($channelId) { $amazonAuth = AmazonAuth::where('channel_id', $channelId)->first(); //my local database channel $isExpired = Carbon::parse($amazonAuth->expires_at)->isPast(); $token = null; if ($isExpired) { $data = [ 'grant_type' => 'refresh_token', 'refresh_token' => $amazonAuth->refresh_token, 'client_id' => TenantService::getLwaClientId(), 'client_secret' => TenantService::getLwaSecret() ]; $response = Http::asForm()->post( 'https://api.amazon.com/auth/o2/token', $data ); if ($response->successful()) { $body = $response->json(); $amazonAuth->access_token = $body['access_token']; $amazonAuth->expires_at = now()->addSeconds($body['expires_in'])->toDateTimeString(); $amazonAuth->save(); $token = $body['access_token']; } else { Log::channel('amazon')->info('Amazon access token refresh failed for amazon auth id: ' . $amazonAuth->id); } } else { $token = $amazonAuth->access_token; } if ($token) { $accessToken = new AccessToken( $token, $amazonAuth->refresh_token, 'refresh_token', (int) $amazonAuth->expires_in, 'refresh_token' ); return $accessToken; } } public function createFeedTest() { $client = new Client(); $factory = new Psr17Factory(); // $httpFactory = new HttpFactory($factory, $factory); $region = 'eu'; $accessToken = $this->getAccessToken(150); $logger = new NullLogger(); $configuration = Configuration::forIAMUser( $getLwaClientId, $getLwaSecret, $getAwsAccessKey, $getAwsSecretKey, ); $sdk = SellingPartnerSDK::create($client, $factory, $factory, $configuration, $logger); $region = Regions::EUROPE; $specification = new CreateFeedDocumentSpecification; $feedDoc = $sdk->feeds()->createFeedDocument( $accessToken, $region, $specification->setContentType('text/xml; charset=utf-8') ); $feedDocID = $feedDoc['feed_document_id']; $urlFeedUpload = $feedDoc['url']; $fileContent = '<?xml version="1.0" encoding="utf-8" ?> <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd"> <Header> <DocumentVersion>1.01</DocumentVersion> <MerchantIdentifier>MYMERCHANTTOKEN</MerchantIdentifier> </Header> <MessageType>Product</MessageType> <PurgeAndReplace>false</PurgeAndReplace> <Message> <MessageID>1</MessageID> <OperationType>Update</OperationType> <Product> <SKU>56789</SKU> <StandardProductID> <Type>ASIN</Type> <Value>B0EXAMPLEG</Value> </StandardProductID> <ProductTaxCode>A_GEN_NOTAX</ProductTaxCode> <DescriptionData> <Title>Example Product Title</Title> <Brand>Example Product Brand</Brand> <Description>This is an example product description.</Description> <BulletPoint>Example Bullet Point 1</BulletPoint> <BulletPoint>Example Bullet Point 2</BulletPoint> <MSRP currency="USD">25.19</MSRP> <Manufacturer>Example Product Manufacturer</Manufacturer> <ItemType>example-item-type</ItemType> <CountryOfOrigin>DE</CountryOfOrigin> <UnitCount>1</UnitCount> <PPUCountType>stück</PPUCountType> <IsExpirationDatedProduct>false</IsExpirationDatedProduct> </DescriptionData> <ProductData> <Health> <ProductType> <HealthMisc> <Ingredients>Example Ingredients</Ingredients> <Directions>Example Directions</Directions> </HealthMisc> </ProductType> </Health> </ProductData> <IsHeatSensitive>false</IsHeatSensitive> </Product> </Message> </AmazonEnvelope>'; dump($feedDoc); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $urlFeedUpload); curl_setopt($curl, CURLOPT_UPLOAD, true); curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=utf-8')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_PUT, 1); curl_setopt($curl, CURLOPT_INFILE, fopen('data://text/plain,' . $fileContent, 'r')); curl_setopt($curl, CURLOPT_INFILESIZE, strlen($fileContent)); #Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); dump($response); curl_close($curl); $specificationNewFeed = new CreateFeedSpecification([ 'feed_type' => 'POST_PRODUCT_DATA', 'marketplace_ids' => ['A1PA6795UKMFR9'], 'input_feed_document_id' => $feedDocID ]); $responseFeed = $sdk->feeds()->createFeed( $accessToken, $region, $specificationNewFeed ); dd($responseFeed); }
我在 mdn web 文档上阅读了有关 XMLHttpRequest 的发送方法的内容。 我无法理解“使用事件传递结果是什么意思” 如果请求是异步的(这是de...
我正在编写一个网络应用程序,可以显示来自 Sonarqube 的代码气味结果,但我也希望它有时可以创建自定义规则。目前,我可以使用
预检选项请求在浏览器中返回 403/forbidden 和不同的标头
我目前正在开发一个混合应用程序,该应用程序也应该稍后通过官方公司域在常规网络浏览器中运行。后端提供RESTful API,支持各种
浏览器如何知道何时重新加载以及何时在单页应用程序中调用 javascript 代码?
我正在学习 React,并且对单页应用程序等概念很陌生。 所以我从单页应用程序教程中了解到的是,只有所需的数据从服务器发送......
HTTP 表单元素与 Fetch 和 XMLHttpRequest
我目前正在学习 Web 开发并遇到了 HTTP。让我困惑的一件事是如何准确地发出 HTTP 请求。在视频中我观看了他们发送 HTTP 请求的主要方式...