สร้างหน้าเว็บไซต์ผ่าน REST API

Aug 22 2020

ฉันต้องการสร้างหน้าไซต์ผ่าน REST API ด้วยชื่อและเนื้อหาของฉันเอง จนถึงตอนนี้ฉันพยายามส่งคำขอ POST แต่พบข้อผิดพลาด:

ในการเพิ่มรายการลงในไลบรารีเอกสารให้ใช้ SPFileCollection.Add ()

โพสต์: <url>/_api/web/lists/GetByTitle('Site Pages')/Items

ร่างกาย:

{
  "__metadata": {
    "type": "SP.Data.SitePagesItem"
  },
  "Title": "It's working?"
}

จากสิ่งที่ฉันเข้าใจ - ก่อนอื่นฉันต้องสร้างหน้าไซต์ (ไฟล์) ใน SharePoint แล้วแก้ไขผ่าน REST อย่างไรก็ตามความต้องการของฉันคือการสร้างรายการทั้งหมดผ่าน REST เท่านั้น

จะทำได้อย่างไร?

คำตอบ

1 spDevAdmin Aug 22 2020 at 18:26

นี่เป็นบทความที่ยอดเยี่ยมที่อธิบายวิธีการทำเช่นนี้ โดยพื้นฐานแล้วจะสร้าง.aspxไฟล์ใหม่ในไลบรารีหน้าไซต์ นี่คือรหัสที่พวกเขาใช้ (เรียกจากเพจบนเว็บเป้าหมาย):

function CreateWikiPage() {

// Get Server relative url of Web(site)
var WebServerRelativeUrl = _spPageContextInfo.webServerRelativeUrl;

// Provide Internal name of the library here
var DocuentLibraryInternalName = "SitePages";

// Provide name of the wiki page to be created
var NewPageName = "NewRESTWikipage.aspx";

// Form relative url of the new page. This will be used in function below
var NewFileUrl = WebServerRelativeUrl + "/" + DocuentLibraryInternalName + "/" + NewPageName;

$.ajax({ // "templateFileType" values in below method // StandardPage. The value = 0. // WikiPage. The value = 1. // FormPage. The value = 2. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + WebServerRelativeUrl + "/" + DocuentLibraryInternalName + "')/Files/AddTemplateFile(urlOfFile='" + NewFileUrl + "',templateFileType=1)", method: "POST", headers: { "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (data, status, xhr) {
        console.log("Success");
    },
    error: function (xhr, status, error) {
        console.log("Failed");
    }
});
}
Sokołow Aug 25 2020 at 15:05
  1. สร้างเทมเพลตของ "รายการที่ทันสมัย" ใน SharePoint ทำตามคำแนะนำนี้เพื่อดำเนินการดังกล่าว

  2. สร้างหน้าไซต์ใหม่ผ่าน REST API โดยใช้เทมเพลตที่บันทึกไว้ เพียงคัดลอกจากโฟลเดอร์เทมเพลตไปยังโฟลเดอร์รูทของหน้าย่อยนั้น:/_api/Web/GetFileByServerRelativeUrl('<source_url>')/CopyTo(strnewurl='<target_url>',bOverwrite=false)

  3. แก้ไขหน้าไซต์ที่สร้างขึ้นใหม่ตามที่คุณต้องการ (เช่นผ่าน REST API)

URL แหล่งที่มาและเป้าหมาย:

source_url - /sites/<your_site>/SitePages/Templates/Your-Template.aspx

target_url - /sites/<your_site>/SitePages/New-Modern-Page.aspx